【问题标题】:How to allow Javascript Methods to share a variable within an Object如何允许 Javascript 方法在对象内共享变量
【发布时间】:2015-09-15 15:06:26
【问题描述】:

我只是想知道是否有办法在对象中拥有一个全局变量。我需要某个对象的所有方法能够共享一个变量,而不是在每个方法中重写相同的变量。

示例: 这就是我现在正在做的事情..

    var myObject = {
          methodOne: function(){
            var myVariable = 'stuff';
            console.log(myVariable);
          },
         methodTwo: function(){
            var myVariable = 'stuff';
            console.log(myVariable);
          }
    }

这就是我想做的……

    var myObject = {
          var myVariable = 'stuff';
          methodOne: function(){
            console.log(myVariable);
          },
         methodTwo: function(){
            console.log(myVariable);
          }
    }

我想我可能有一些语法错误,但我尝试了不同的方法,这些方法无法运行。令人惊讶的是,我无法在互联网上找到该主题的直接答案。

【问题讨论】:

    标签: javascript object scope global-variables


    【解决方案1】:

    首先,将myVariable设置为myObject的属性,然后你可以在你的函数中使用this.myVariable来访问它。

    var myObject = {
          myVariable: 'stuff',
          methodOne: function(){
            // If you use myObject.xxx to call the function, then
            // `this` will be the reference of `myObject`, so you
            // can get `myVariable` by `this.myVariable`.
            console.log(this.myVariable);
          },
         methodTwo: function(){
            console.log(this.myVariable);
          }
    }
    
    myObject.methodOne();
    myObject.methodTwo();

    或者,如果您不希望其他人可以访问 myVariable

    // Create a function that will return an Object, and execute it immediately.
    // By this way, myVariable now is only visible to the 2 method in the return object
    // as they're in the same function scope.
    var myObject = (function() {
      var myVariable = 'stuff';
      
      return {
        methodOne: function(){
          console.log(myVariable);
        },
        methodTwo: function(){
          console.log(myVariable);
        }
      };
    })();
    
    console.log(myObject); // Only 2 methods in myObject
    // But both still share the same var myVariable
    myObject.methodOne();  
    myObject.methodTwo();

    【讨论】:

    • 太棒了,我知道事情就是这么简单。 'this'关键字'是这种情况下的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    相关资源
    最近更新 更多