![](/img/trans.png)
[英]Why var eva = function() {} does't work for addEventListener()
[英]Why does it work? JS function and var
在編寫一些 JS 的過程中,腳本完全按照我的預期工作,但在我給它提供了可以使用的編號之前。
現在腳本中進一步說明了數字,我很好奇,這就是為什么會起作用嗎? JS 中的變量是否考慮了稍后在函數內部聲明的變量?
我困惑的特定部分: if (lastrowIDnumInt === 0)
因為在 else 之前沒有聲明 var 並給定一個值。
請如果有人可以解釋這是否正確工作,如果是,請參考為什么?
這是片段:
function voidall() {
if (lastrowIDnumInt === 0){ // references lastrowIDnumInt, no tengo como haces without prior reference
alert("You cannot remove any items that do not exist!");
} else {
var activetableID = $("li.till_table_button.active").attr('id');
// alert(activetableID);
var tablenumber = $("#"+activetableID).data("tableref");
// alert(tablenumber); //testing
var lastrowid = $( "#till__tablepanel_table_"+tablenumber+" tr:last").attr("id");
var idReference = lastrowid.substr(0, lastrowid.indexOf('row_')); //gets the beggining id refernces without number
// alert(idReference); //testing
var fullReference = idReference+"row_";
// alert(fullReference); //testing
var lastrowIDnum = lastrowid.substring(lastrowid.indexOf("row_") + 4); //take number for row by removing string contents
lastrowIDnumInt = parseInt(lastrowIDnum); //turn string number into integer
while ( lastrowIDnumInt > 0 ) {
$( "#till__tablepanel_table_"+tablenumber+" tr:last").remove();
lastrowIDnumInt--;
}
}
}
函數中的所有var
聲明都被視為出現在函數的頂部。 這就是所謂的“吊裝”。
請注意,聲明被視為在頂部,而不是初始化。 這意味着:
function foo() {
if (something === 0) {
alert("zero");
}
else {
var something = 0;
alert("not zero"); // <-- this
}
}
這被視為看起來像這樣:
function foo() {
var something;
if (something === 0) { // <-- undefined here
alert("zero");
}
else {
something = 0;
alert("not zero"); // <-- this
}
}
因為var
被提升到函數作用域的頂部。 換句話說,無論條件如何,您的變量都已定義,但它們只會在else
塊中分配值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.