考虑以下代码:
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();
输出是: 5个 不明确的 11
为了保持代码阅读简单,我更喜欢将方法添加到原型(prototype),如 countBranches()
,而不是像 countFruits()
这样的内部构造函数。但是,缺点是原型(prototype)函数不能访问 Tree 的私有(private)变量。有办法吗?
最佳答案
However, the disadvantage is that the prototype functions can not access Tree's private variables. Is there a way to do that?
所以你想要一个不是私有(private)的私有(private)变量。不,没有办法做到这一点。任何函数都不能访问其他函数的内部状态。
但是,如果您将 smallBranches
设为私有(private)的目的是防止它被覆盖,您可以在添加访问器时将其设为私有(private):
var Tree = function() {
// private variables in closure
var smallBranches = 10;
...
this.getSmallBranches = function() { return smallBranches; };
};
Tree.prototype.countBranches = function() {
console.log(this.getSmallBranches());
};
或者,如果您希望能够直接说出 this.smallBranches
,请将其设为只有一个 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
};
关于javascript - 原型(prototype)方法可以访问构造函数的上下文(闭包),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40797513/