在實現模塊模式時,私有函數如何訪問模塊的私有屬性?我還沒有看到任何開發人員這樣做的例子。有什麼理由不這樣做?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();
}
};
})();
工作正常: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