Reputation: 4605
Consider this:
var Foo = function Foo () {
var numberVar = 0;
fooPrototype = {
getNumberVar: function () {
return numberVar;
},
setNumberVar: function (val) {
this.numberVar = val;
}
}
return fooPrototype;
};
var foo = new Foo();
Alternatively, look at this:
var Bar = function Bar() {
var numberVar = 0;
};
Bar.prototype = {
getNumber: function () {
return this.numberVar;
},
setNumber: function (val) {
this.numberVar = val;
}
};
var bar = new Bar();
They both do the same thing, in that they allow for public / private members. Is there any benefit to doing this one way or the other?
Upvotes: 0
Views: 57
Reputation: 708046
Your logic here is based on a faulty assumption. In your second implementation, the constructor variable numberVar
is never used. You have no code that can reach it and thus you are not using a private variable in the second code block.
Your methods in that second implementation are accessing an object property named numberVar
which is publicly accessible as a property on the object which is different than the local variable of the same name in your constructor. You cannot have private variables in your second implementation because your prototype-declared methods are not declared in a private scope.
Here's what happens in your second code block:
var Bar = function Bar() {
// this variable is never used as there is no code in this scope
// that can reach this variable. In fact, it is garbage collected
// immediately
var numberVar = 0;
};
Bar.prototype = {
getNumber: function () {
return this.numberVar;
},
setNumber: function (val) {
// sets a public property on the object
this.numberVar = val;
}
};
var bar = new Bar();
bar.setNumber(10);
console.log(bar.numberVar); // 10, this property is public
For a general discussion of methods declared in the constructor vs. prototype-defined methods, see this discussion:
Advantages of using prototype, vs defining methods straight in the constructor?
Upvotes: 1