2011-12-20 117 views
13

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

工作正常:http://jsfiddle.net/DREKt/儘管您可能希望在'_privateIncrement'前加上'var'聲明。 – Dennis 2011-12-20 18:10:17

+0

如果'number'沒有在模塊的閉包中綁定,並且是對象的一部分,那麼您可能需要使用'apply()'或'call()'在正確的上下文中調用私有方法。 '_privateIncrement.call(this)' – 2011-12-20 18:15:35

回答

10

在實現模塊模式,怎麼辦私人聚會訪問模塊的私有財產?

的性能範圍,所以他們 「只管去做」

不工作。

是的,它的確如此。

_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 
+1

+1雖然我認爲OP通過說「_how做私有函數訪問module_的私有屬性」嘗試解釋他/她想訪問返回對象的屬性(例如'getNumber ()'方法)從'_privateIncrement()'函數中。 – Tadeck 2011-12-20 18:28:40

+0

昆汀是對的。我在系統中的其他地方發現了一個拋出私有變量的錯誤。謝謝。 – Thomas 2011-12-20 18:32:44

3

一種可以替代的具有私有方法能夠訪問this是使用callapply方法。

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外的構造。

相關問題