I've been wondering about JavaScript's prototypal nature, and the benefits of it, and have e down to the following list :
1) Inheritance
cat.prototype = animal
2) Memory Efficiency
a.prototype.b = function() {}
var a1 = new a();
var a2 = new a();
Then a1.b and a2.b are essentially the same object, where as :
var a = function() {
this.b = function() {};
}
var a1 = new a();
var a2 = new a();
a1.b and a2.b would be different function objects and take up more memory.
3) Adding methods/fields to multiple, already created, 'out in the wild' objects.
var a = function() {}
var a1 = new a();
var a2 = new a();
a.prototype.b = function() {}
a1.b();
a2.b();
So the question is, are these correct?
... and are there any other benefits I've missed?
Cheers!
I've been wondering about JavaScript's prototypal nature, and the benefits of it, and have e down to the following list :
1) Inheritance
cat.prototype = animal
2) Memory Efficiency
a.prototype.b = function() {}
var a1 = new a();
var a2 = new a();
Then a1.b and a2.b are essentially the same object, where as :
var a = function() {
this.b = function() {};
}
var a1 = new a();
var a2 = new a();
a1.b and a2.b would be different function objects and take up more memory.
3) Adding methods/fields to multiple, already created, 'out in the wild' objects.
var a = function() {}
var a1 = new a();
var a2 = new a();
a.prototype.b = function() {}
a1.b();
a2.b();
So the question is, are these correct?
... and are there any other benefits I've missed?
Cheers!
Share Improve this question asked Aug 11, 2010 at 20:19 lucas1000001lucas1000001 2,7501 gold badge25 silver badges22 bronze badges 1- well-reasoned. it's basically the Javascript version of class vs. instance properties/methods – Jason S Commented Aug 11, 2010 at 20:38
2 Answers
Reset to default 5Those are all correct.
Of course, there are "drawbacks" as well:
No closures
function a() {
var ival = 0;
this.start = function(){ ival = setInterval(function(){ }, 300); }
this.finish = function(){ clearTimeout(ival); }
}
pare to:
function a() {
this.ival = 0;
}
a.prototype.start = function(){ this.ival = setInterval(function(){ }, 300); }
a.prototype.finish = function(){ clearTimeout(this.ival); }
http://en.wikipedia/wiki/Prototype-based_programming#Comparison_with_class-based_models
Also, please see the discussion of prototype inheritance in the answers to this:
prototype based vs. class based inheritance