2011-12-20 118 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外的构造。

相关问题