在Javascript中的函数之间共享变量
我有如下代码:在Javascript中的函数之间共享变量,javascript,Javascript,我有如下代码: MyClass = { init: function(){ marker = 0; //I call foo() and bar() from here }, foo: function(){ //I want to access & update marker here }, bar: function(){ //This function also accesses updates marker } }
MyClass = {
init: function(){
marker = 0;
//I call foo() and bar() from here
},
foo: function(){
//I want to access & update marker here
},
bar: function(){
//This function also accesses updates marker
}
};
我可以通过将标记作为参数传递给函数来访问它,但我将无法更新它
那么,如何创建一个变量标记
,以便所有三个函数都可以共享它呢?我不想在MyClass之外编写任何代码,而不是在init中,它现在所在的位置
MyClass = {
// marker is in MyClass now
marker: 0,
init: function(){
console.log(this.marker);
//I call foo() and bar() from here
},
foo: function(){
//I want to access & update marker here
},
bar: function(){
//This function also accesses updates marker
}
};
将marker
放在MyClass中,而不是它现在所在的init中
MyClass = {
// marker is in MyClass now
marker: 0,
init: function(){
console.log(this.marker);
//I call foo() and bar() from here
},
foo: function(){
//I want to access & update marker here
},
bar: function(){
//This function also accesses updates marker
}
};
如果执行MyClass.init()
,它将在控制台中打印8
如果您执行MyClass.init()
,它将在控制台中打印8。尝试将marker
设置为MyClass
的属性。尝试将marker
设置为MyClass
的属性。我得到的是预期的“:”,而不是在jslint中看到的“=”。
。(在我声明marker=0的行上)@shadyabhi:它应该是marker:0
,就像其他属性一样。谢谢。这很容易。我将在接下来的7分钟内排除答案。我得到的是Expected':'而不是在jslint中看到的“=”。
。(在我声明marker=0的行上)@shadyabhi:它应该是marker:0
,就像其他属性一样。谢谢。这很容易。我将在接下来的7分钟内给出答案。