javascript strict mode

來源:互聯網
上載者:User

標籤:alert   number   rod   文法   就是   cat   erro   錯誤   聲明   

ECMAScript 版本5是目前最廣泛使用的js版本。

其中的一個重要feature strict mode很多人不是很清除和理解。

什麼是strict mode?

strict mdoe是一種強制js解釋引擎以一種和非stric mode不同的語義的方式來解釋javascript代碼。運行於script mode的代碼有以下幾個特徵:

1. 剔除一些句法和語義功能,也就是說,你不能象傳統js那樣隨心所欲

2. 修正部分功能的語義,即:一部分代碼在strict mode和非strict mode下執行的語義是不同的。

3. 如果有文法或者語義的歧義,在stric mode下直接報出錯誤,而非隱含運行;

4. stric mode僅僅應用於程式碼片段,也就是說,你不能將strict mode一次性應用到所有js檔案中,除非你concat所有的js檔案.

stric mode出現的主要白目的是在js開發過程中,強制一些運行時的discipline. 我總是感覺js實在太過靈活,而stric mode就是將這個靈活做以下限制。很多時候之前必須由資深工程師自己注意的tricky部分,那麼現在就由stric mode強加進來了。比如看看下面這段代碼,你看有什麼問題嗎?實際上"stric mode"下,js引擎就會報錯:

function findProduct(numbers) {    "use strict";    var product = 0,        len = numbers.length;    for(var i = 0; i < len; ++i) {        prodct = product * numbers[i]; // ReferenceError: Variable undefined in strict mode    }    return product;}

 

瀏覽器支援情況:

幾乎所有的現代瀏覽器都在他們的js引擎中支援strict mode. IE10以上都支援strict mode,

strict mode contexts:

"use strict";alert("Look ma! Strict mode!");

幾種使能方式:

// global code<script>  "use strict";  // global strict mode code here</script>// 2. Eval code:eval("‘use strict‘; // strict code here");// or invoked from strict mode code:"use strict";eval("// strict code here");// function code:function foo() {    "use strict";    // strict code here}// Functions declared in strict mode code inherit the strictness:function foo() {    "use strict";    var bar = function () {        // strict code here    };    bar();}

 strict mode到底有哪些新的限制呢?

1. 標示符必須在他們被賦值前聲明:

2. 對於沒有context的function call不會自動賦予context,比如如果函數被調用不給一個obj.method這種方式的話,函數並不會給於this為window對象。

function foo() {    // prints "true"    print(this === window);}foo();function foo() {    "use strict";    // prints "false"    print(this === window);}foo();

3. reserved keywords不能用於標示變數名

"use strict";var yield; // SyntaxError: Expected identifier

 

https://blogorama.nerdworks.in/javascriptstrictmoderestrictio/

javascript strict mode

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.