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

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

函數內部的全局變量不能在外部訪問

函數內部的全局變量不能在外部訪問

飲歌長嘯 2023-01-06 11:01:17
如果我理解正確,在函數內部不使用關鍵字 var 聲明變量將創建一個全局范圍的變量。但是當從其容器函數外部訪問變量時,我得到這個“ReferenceError: oopsGlobal is not defined”。,,, // Declare the myGlobal variable below this linevar myGlobal = 10 function fun1() {  // Assign 5 to oopsGlobal Here  oopsGlobal = 5}// Only change code above this linefunction fun2() {  var output = "";  if (typeof myGlobal != "undefined") {    output += "myGlobal: " + myGlobal;  }  if (typeof oopsGlobal != "undefined") {    output += " oopsGlobal: " + oopsGlobal;  }  console.log(output);}console.log(oopsGlobal) // ReferenceError: oopsGlobal is not defined,,,
查看完整描述

2 回答

?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

您編寫了代碼,但從未調用過它。fun1并且fun2永遠不會運行。我在下面添加了一行,它調用了fun1()導致分配發生的函數。


這更像是提供演示的答案——您很可能不想實際編寫具有全局變量或像這樣的副作用的代碼。如果您正在為瀏覽器編寫軟件,使用window或globalThis存儲您的全局狀態也可能使它更清晰。


// Declare the myGlobal variable below this line

var myGlobal = 10 


function fun1() {

  // Assign 5 to oopsGlobal Here

  oopsGlobal = 5

}


fun1(); // You wrote the functions previous, but you never CALLED them.


// Only change code above this line


function fun2() {

  var output = "";

  if (typeof myGlobal != "undefined") {

    output += "myGlobal: " + myGlobal;

  }

  if (typeof oopsGlobal != "undefined") {

    output += " oopsGlobal: " + oopsGlobal;

  }

  console.log(output);

}


console.log(oopsGlobal) // ReferenceError: oopsGlobal is not defined


查看完整回答
反對 回復 2023-01-06
?
人到中年有點甜

TA貢獻1895條經驗 獲得超7個贊

發生這種情況是因為您實際上從未跑步過fun1()。如果你不調用一個函數,里面的代碼將永遠不會被執行。


參考錯誤:


 // Declare the myGlobal variable below this line

var myGlobal = 10 


function fun1() {

  // Assign 5 to oopsGlobal Here

  oopsGlobal = 5

}


// Only change code above this line


function fun2() {

  var output = "";

  if (typeof myGlobal != "undefined") {

    output += "myGlobal: " + myGlobal;

  }

  if (typeof oopsGlobal != "undefined") {

    output += " oopsGlobal: " + oopsGlobal;

  }

  console.log(output);

}


console.log(oopsGlobal) // ReferenceError: oopsGlobal is not defined




沒有 ReferenceError(注意是之前fun1()調用的) console.log()

 // Declare the myGlobal variable below this line

var myGlobal = 10 


function fun1() {

  // Assign 5 to oopsGlobal Here

  oopsGlobal = 5

}


// Only change code above this line


function fun2() {

  var output = "";

  if (typeof myGlobal != "undefined") {

    output += "myGlobal: " + myGlobal;

  }

  if (typeof oopsGlobal != "undefined") {

    output += " oopsGlobal: " + oopsGlobal;

  }

  console.log(output);

}


fun1()

console.log(oopsGlobal)


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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