[英]Frontend Developer Interview Coding Questions: a not defined and b is defined?
我從前端開發人員面試編碼問題中得到了這個問題。 為什么下面的代碼片段打印它打印的內容? 我最初認為它會拋出一個 ReferenceError“b 未定義” (因為它看起來像“我們即將將一個未定義的變量b
分配給一個預期的已定義變量a
)但后來結果是“b 已定義,a 未定義”定義,並且沒有錯誤”?什么是var a = b = 3;
在 javascript 中被調用?
(function(){ var a = b = 3; })(); console.log("a defined? " + (typeof a !== 'undefined')); console.log("b defined? " + (typeof b !== 'undefined'));
var
僅適用於a
而不適用於b
。 因此,由於b
沒有用var
定義並被賦值,所以它變成了全局的。
如果你重寫函數的工作方式,你可以清楚地看到b
沒有var
(function(){ var a; b = 3; a = b; })(); console.log("a defined? " + (typeof a !== 'undefined')); console.log("b defined? " + (typeof b !== 'undefined'));
因為var a = b = 3;
意味着var a = window.b = 3;
您正在從窗口訪問 b。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.