【问题标题】:Javascript accessing object variable from another callback without placing variable in global scopeJavascript从另一个回调访问对象变量而不将变量放在全局范围内
【发布时间】:2014-10-26 14:34:58
【问题描述】:

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

代码

var a = {

    load: function(){

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

    },

    add : function (b){

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


};

【问题讨论】:

    标签: javascript callback scope global-variables


    【解决方案1】:

    使用闭包:

    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.
    

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

    【讨论】:

    • module.add() 返回 undefined 而不是 25
    • 我的错,不需要传递任何东西给add。
    【解决方案2】:
    // 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; 
    
    // ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 2019-10-17
      • 2013-06-12
      • 2013-12-25
      相关资源
      最近更新 更多