我只是想知道是否有一种方法可以在对象内拥有全局变量。我需要某个对象的所有方法能够共享一个变量,而不是在每个方法中重写相同的变量。
的例子:这就是我现在正在做的……
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);
}
}
我想我可能有一些语法错误,但我已经尝试了不同的方法和方法不会运行。令人惊讶的是,我在网上找不到这个问题的直接答案。
首先,将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();