JavaScript 模块模式:私有方法如何访问模块的作用域?
在实现模块模式时,私有函数如何访问模块的私有属性?我还没有看到任何开发人员这样做的例子。有什么理由不这样做吗?
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? I haven't seen any examples where developers do this. Is there any reason not to?
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();
}
};
})();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这些属性在范围内,所以它们“就是这样”
是的,确实如此。
是的,确实如此。
请参阅以下内容的实时示例:
The properties are in scope, so they "just do"
Yes, it does.
Yes, it does.
See live example of the following:
拥有可以访问
this
的私有方法的另一种替代方法是使用call
或apply
方法。当然,如果您计划拥有该对象的多个实例,您可以将 use_restroom 和 buy_food 移动到构造函数之外的原型和 private_stuff 。
One alternative to have private methods with access to the
this
is by using thecall
orapply
methods.Of course you would move the use_restroom and buy_food to a prototype and private_stuff outside of the constructor if you were planning on having multiple instances of this object.