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

Javascript accessing object variable from another callback without placing variable in global scope

本文关键字:变量 范围内 全局 另一个 回调 访问 对象 Javascript      更新时间:2023-09-26

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

代码

var a = {
    load: function(){
        var b = 25;
        console.log(b);
    },
    add : function (b){
        console.log('The value of b is '+ b);
    }

};

使用闭包:

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.

现在,所有"私有"变量都直接作用于模块,并且不影响全局作用域。

// 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; 
// ...