在实现模块模式时,私有(private)函数如何访问模块的私有(private)属性?我还没有看到开发人员这样做的任何例子。有什么理由不这样做吗?
var module = (function(){
// private property
var number = 0;
// private method
_privateIncrement = function(){
// how do I access private properties here?
number++;
};
// public api
return {
// OK
getNumber: function(){
return number;
},
// OK
incrNumber: function(){
number++;
},
// Doesn't work. _privateIncrement doesn't have
// access to the module's scope.
privateIncrNumber: function(){
_privateIncrement();
}
};
})();
最佳答案
When implementing the module pattern, how do private functions access the private properties of the module?
属性在范围内,所以它们“只是做”
Doesn't work.
是的,确实如此。
_privateIncrement
doesn't have access to the module's scope.
是的,确实如此。
参见 live example以下:
var module = (function(){
// private property
var number = 0;
// global method
_privateIncrement = function(){
number++;
};
// public api
return {
// OK
getNumber: function(){
return number;
},
// OK
incrNumber: function(){
number++;
},
// Does work!
privateIncrNumber: function(){
_privateIncrement();
}
};
})();
// Show default value
document.body.innerHTML += (module.getNumber());
// Increment
module.privateIncrNumber();
// Show new value
document.body.innerHTML += (module.getNumber());
// Increment (since _privateIncrement was defined as a global!)
_privateIncrement();
// Show new value
document.body.innerHTML += (module.getNumber());
// Output: 012
关于JavaScript 模块模式 : How do private methods access module's scope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8579885/