對於初學者來說:這是不是你應該如何在JavaScript中聲明一個變量:
attackValue = $(this).text();
這會弄亂「程序」可變空間。您應該始終使用關鍵字var
在javascript中聲明變量。
當我想在click()之外使用attackValue時它不會被定義。
這取決於你想在何時何地使用它。考慮following code:
var attackValue = 'some value';
function setValue() {
attackvalue = 'some other value';
}
console.log(attackvalue); // this would output some value, because the function hasn;t run yet
setValue();
不過,如果你would do:
var attackValue = 'some value';
function setValue() {
attackValue = 'some other value';
}
setValue();
console.log(attackValue); // this would output some other value, because the function did already run
注意上面的代碼應該在closure運行。或者它仍會混亂變量空間(即使使用var
)關鍵字。所以它看起來更像是:
(function() { // yay closure, now all variables defined in here will stay in here
var attackValue = 'some value';
function setValue() {
attackValue = 'some other value';
}
setValue();
console.log(attackValue); // this would output some other value, because the function did already run
})();
如果OP在那裏聲明'attackValue'而沒有'var'關鍵字。它是全球性的,應該可以在功能之外訪問。儘管使用該代碼片段是不可能的。 – PeeHaa 2012-03-31 00:17:41