2014-10-26 34 views
-2

我有以下情形。我有一個帶有兩個回調方法的對象'a',但是一個回調需要訪問另一個回調變量值(進行修改/讀取值/更新值)。我想知道如何在不將變量b放入全局範圍的情況下構造此代碼的最佳方法。下是代碼和一個jsfiddle從另一個回調中訪問對象變量而不將變量置於全局範圍內

代碼

var a = { 

    load: function(){ 

     var b = 25; 
     console.log(b); 

    }, 

    add : function (b){ 

     console.log('The value of b is '+ b); 
    } 


}; 

回答

3

使用閉包:

var module = (function() { 
    var b; //Scoped to this module 

    return { //Return object with methods 
     load: function() { 
      b = 25; //This refers to the module's b 
      console.log(b); 
     }, 
     add: function() { 
      console.log('The value of b is '+ b); 
     } 
    }; 
})(); //Self invoking function, invokes instantly. 

module.load(); //b is now 25. 
module.add(); //The value of b is 25 
console.log(b); //undefined, out of scope. 

現在所有的 「私有」 變量直接作用域到模塊,並且不會影響全局範圍。

+0

module.add()返回undefined不是25 – devdar 2014-10-26 14:59:55

+1

我的壞,無需任何傳遞給'add'。 – 2014-10-26 15:02:58

0
// Alternative 1: Using a "private" variable 
function A(b) { 
    // seal b in closure 
    var b = b; 

    this.load = function(){ 
     b = 25; 
     console.log(b); 
    }; 

    this.add = function(){ 
     console.log('The value of b is '+ b); 
    }; 

    this.getB = function(){ 
     return b; 
    }; 
} 

// Alternative 2: Using a object property 
function A(b) { 
    // seal b in closure 
    this.b = b; 

    this.load = function(){ 
     this.b = 25; 
     console.log(this.b); 
    }; 

    this.add = .add = function(){ 
     console.log('The value of b is '+ this.b); 
    }; 
} 

var a = new A('foo'); 
var callback = a.load; 

// ...