Reputation: 67
Consider the following code:
var Tree = function() {
// private variables in closure
var fruits = 5;
var smallBranches = 10;
// public variables
this.bigBranches = 11;
this.countFruits = function() {
console.log(fruits);
};
};
Tree.prototype.countBranches = function() {
console.log(this.smallBranches);
console.log(this.bigBranches);
};
var tree = new Tree();
tree.countFruits();
tree.countBranches();
The output is: 5 undefined 11
To keep the code reading simple, I prefer to add methods to prototype like countBranches()
instead of inside construction functions like countFruits()
. However, the disadvantage is that the prototype functions can not access Tree's private variables. Is there a way to do that?
Upvotes: 4
Views: 61
Reputation:
However, the disadvantage is that the prototype functions can not access Tree's private variables. Is there a way to do that?
So you want a private variable which is not private. No, there is no way to do that. No more than any function can access some other function's internal state.
However, if your objective in making smallBranches
private is to prevent it from being overwritten, you can keep it private while adding an accessor:
var Tree = function() {
// private variables in closure
var smallBranches = 10;
...
this.getSmallBranches = function() { return smallBranches; };
};
Tree.prototype.countBranches = function() {
console.log(this.getSmallBranches());
};
Or, if you prefer to be able to say this.smallBranches
directly, make it an instance property with only a getter:
var Tree = function() {
// private variables in closure
var smallBranches = 10;
Object.defineProperty(this, 'smallBranches', {
get() { return smallBranches; }
});
}
Tree.prototype.countBranches = function() {
console.log(this.smallBranches);
this.smallBranches = 42; // will fail
};
Upvotes: 5
Reputation: 11420
Actually the approach of associating member functions through prototype, outside constructor is the standard approach for adding member function to a type in javascript. You are getting undefined, due to not associating smallBranches
variables with current object. Thus, it ends up as a local variable and not accessible outside constructor function. You have to make it as a member variable.
Change you code, as given below :-
var Tree = function() {
// private variables in closure
var fruits = 5;
this.smallBranches = 10;
// public variables
this.bigBranches = 11;
this.countFruits = function() {
console.log(fruits);
};
};
Upvotes: 0