亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 setTimeout 函數中的變量無法使用 = || 正確訪問 window.global

為什么 setTimeout 函數中的變量無法使用 = || 正確訪問 window.global

慕慕森 2023-05-19 19:54:03
這是代碼:window.test1 = 'Jack';setInterval(function(){  console.log(test1); // Works fine, expect output: "Jack"}, 2000);刷新窗口并輸入:window.test1 = 'Jack';setInterval(function(){  var test1 = test1 || [];  console.log(test1); // Works bad, get [] instead of "Jack"}, 2000);為什么會這樣?
查看完整描述

2 回答

?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

為什么會這樣?


這是因為變量提升


所以這


window.test1 = 'Jack';

setInterval(function(){

  var test1 = test1 || [];

  console.log(test1); // Works bad, get [] instead of "Jack"

}, 2000);

實際上是這個


window.test1 = 'Jack';

setInterval(function(){

  // declaring local variable test1 and it has no value so it holds `undefined`

  var test1;

  // so now you gett [] instead because the variable test1 is falsy `undefined`

  test1 = test1 || [];

  console.log(test1); // Works bad, get [] instead of "Jack"

}, 2000);


查看完整回答
反對 回復 2023-05-19
?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

test1發生這種情況是因為您在函數和變量提升中聲明了變量。使用您的示例和修改后的版本,我們可以看到第一個超時函數顯示的結果與我們預期的結果相同,避免此問題的一種方法是第二個超時函數中的示例(使用不同的變量描述符):


window.test1 = 'Jack';

setTimeout(function() {

? var test1 = test1 || [];

? console.log('timeoutFunction1', test1); // Works bad, get [] instead of "Jack"

}, 2000);

setTimeout(function() {

? var test2 = test1 || []; // Works fine since we're not declaring `test1` in this function

? console.log('timeoutFunction2', test2);

}, 3000);


查看完整回答
反對 回復 2023-05-19
  • 2 回答
  • 0 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號