JavaScript模块模式:私有方法如何访问模块的范围?
问题描述:
在实现模块模式时,私有函数如何访问模块的私有属性?我还没有看到任何开发人员这样做的例子。有什么理由不这样做?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();
}
};
})();
答
在实现模块模式,怎么办私人聚会访问模块的私有财产?
的性能范围,所以他们 “只管去做”
不工作。
是的,它的确如此。
_privateIncrement
无法访问模块的范围。
是的,它的确如此。
请参见下面的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
答
一种可以替代的具有私有方法能够访问this
是使用call
或apply
方法。
function Restaurant()
{
this.mongoose = 'beans';
this.freedom = {bear:'love',a:'12'};
var myPrivateVar;
var private_stuff = function() // Only visible inside Restaurant()
{
myPrivateVar = "I can set this here!";
this.mongoose = 12;
}
this.use_restroom = function() // use_restroom is visible to all
{
private_stuff();
}
this.buy_food = function() // buy_food is visible to all
{
private_stuff();
}
private_stuff.call(this);
}
var bobbys = new Restaurant();
当然,如果你是在具有此对象的多个实例规划,你会移动use_restroom和buy_food的原型和private_stuff外的构造。
工作正常:http://jsfiddle.net/DREKt/尽管您可能希望在'_privateIncrement'前加上'var'声明。 – Dennis 2011-12-20 18:10:17
如果'number'没有在模块的闭包中绑定,并且是对象的一部分,那么您可能需要使用'apply()'或'call()'在正确的上下文中调用私有方法。 '_privateIncrement.call(this)' – 2011-12-20 18:15:35