ts和js中let和var定義變數的區別
阿新 • • 發佈:2019-01-29
javascript 嚴格模式
第一次接觸let關鍵字,有一個要非常非常要注意的概念就是”JavaScript 嚴格模式”,比如下述的程式碼執行就會報錯:
let hello = 'hello world.'; console.log(hello);
錯誤資訊如下:
let hello = 'hello world.'; ^^^ SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode ...
解決方法就是,在檔案頭新增”javascript 嚴格模式”宣告:
'use strict'; let hello = 'hello world.'; console.log(hello);
更多更詳細的關於”javascript 嚴格模式”說明,請參考阮一峰的部落格
《Javascript 嚴格模式詳解》
let和var關鍵字的異同
聲明後未賦值,表現相同
'use strict'; (function() { var varTest; let letTest; console.log(varTest); //輸出undefined console.log(letTest); //輸出undefined }());
使用未宣告的變數,表現不同:
(function() { console.log(varTest); //輸出undefined(注意要註釋掉下面一行才能執行) console.log(letTest); //直接報錯:ReferenceError: letTest is not defined var varTest = 'test var OK.'; let letTest = 'test let OK.'; }());
重複宣告同一個變數時,表現不同:
'use strict'; (function() { var varTest = 'test var OK.'; let letTest= 'test let OK.'; var varTest = 'varTest changed.'; let letTest = 'letTest changed.'; //直接報錯:SyntaxError: Identifier 'letTest' has already been declared console.log(varTest); //輸出varTest changed.(注意要註釋掉上面letTest變數的重複宣告才能執行) console.log(letTest); }());
變數作用範圍,表現不同
'use strict'; (function() { var varTest = 'test var OK.'; let letTest = 'test let OK.'; { var varTest = 'varTest changed.'; let letTest = 'letTest changed.'; } console.log(varTest); //輸出"varTest changed.",內部"{}"中宣告的varTest變數覆蓋外部的letTest宣告 console.log(letTest); //輸出"test let OK.",內部"{}"中宣告的letTest和外部的letTest不是同一個變數 }());
Egret下:
使用未定義的let:
class Test { public name:string = "Test"; public run(){ console.log(a); //該行報錯 Block-scoped variable 'a' used before its declaration. console.log(b); let a; var b; } }
重複定義let:
class Test { public name:string = "Test"; public run(){ let a; //該行報錯 Cannot redeclare block-scoped variable 'a'. var b; let a; var b; //該行報錯 Cannot redeclare block-scoped variable 'a'.
} }
變數範圍:
class Test { public name:string = "Test"; public run(){ let a = 1; var b = 2; { let a = 2; var b = 2; } console.log(a); //1 console.log(b); //2 } }