Javascript从另一个回调访问对象变量而不将变量放在全局范围内

时间:2014-10-26 14:34:58

标签: javascript callback scope global-variables

我有以下情况。我有一个带有两个回调方法的对象'a',但是一个回调需要访问另一个回调变量值(用于修改/读取值/更新值)。我想知道在不将变量b放入全局范围的情况下构造此代码的最佳方法是什么。下面是代码和jsfiddle

代码

var a = {

    load: function(){

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

    },

    add : function (b){

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


};

2 个答案:

答案 0 :(得分: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.

现在所有"私人"变量直接作用于模块,不会影响全局范围。

答案 1 :(得分: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; 

// ...