如何允许Javascript方法在Object中共享变量

时间:2015-09-15 15:06:26

标签: javascript object scope global-variables

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

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

    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);
          }
    }

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

1 个答案:

答案 0 :(得分:0)

首先,将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();