js中let和var定義變數的區別

來源:互聯網
上載者:User

標籤:javascrip   class   nbsp   hello   console   方法   tle   com   cee   

javascript strict 模式

第一次接觸let關鍵字,有一個要非常非常要注意的概念就是”JavaScript strict 模式”,比如下述的代碼運行就會報錯:

let hello = ‘hello world.‘;console.log(hello);
  • 1
  • 2
  • 1
  • 2

錯誤資訊如下:

let hello = ‘hello world.‘;^^^SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode    ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

解決方案就是,在檔案頭添加”javascript strict 模式”聲明:

‘use strict‘;let hello = ‘hello world.‘;console.log(hello);
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

更多更詳細的關於”javascript strict 模式”說明,請參考阮一峰的部落格 
《Javascript strict 模式詳解》

let和var關鍵字的異同聲明後未賦值,表現相同
‘use strict‘;(function() {  var varTest; let letTest; console.log(varTest); //輸出undefined console.log(letTest); //輸出undefined}());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
使用未聲明的變數,表現不同:
(function() {  console.log(varTest); //輸出undefined(注意要注釋掉下面一行才能運行) console.log(letTest); //直接報錯:ReferenceError: letTest is not defined var varTest = ‘test var OK.‘; let letTest = ‘test let OK.‘;}());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
重複聲明同一個變數時,表現不同:
‘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);}());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
變數作用範圍,表現不同
‘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不是同一個變數}());

js中let和var定義變數的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.