Reputation: 8961
I think that there is a significant amount of overlap between what you can achieve with closures and what you can achieve with constructors in Javascript - some slight differences in the API to the different structures notwithstanding.
This code:
function Animal1(name) {
this.name = name;
};
var x = new Animal1('x');
console.log(x.name); // x
Seems functionally quite similar to this code:
function Animal2(name) {
var name = name;
var getName = function() {return name;};
return {name: getName};
}
var y = Animal2('y');
console.log(y.name()); // y
Except that x gets assigned a __proto__
property. If you weren't going to use prototypal inheritance in your code, how would you choose between closures and constructors such as above?
i.e. which takes more memory? which is more efficient? are there other things to consider? etc. etc.
Upvotes: 0
Views: 58
Reputation: 2503
function Animal2(name) {
var name = name;
var getName = function() {return name;};
return {name: getName};
}
var y = Animal2('y');
console.log(y.name()); // y
In the preceding code the getName function is generated every time Animal2 is called. In this case of course it's trivial but this method both requires more memory and is slower. A benefit of this method can be that it allows you a degree of encapsulation as you can have private variables shared between functions that are not exposed.
Take a look at the following for more information: https://developers.google.com/speed/articles/optimizing-javascript
Upvotes: 1