嚴(yán)格模式:由ECMA-262規(guī)范定義的JavaScript標(biāo)準(zhǔn),對javascrip的限制更強(qiáng)。
(非嚴(yán)格的模式,被稱為“馬虎模式/稀松模式/懶散模式”。)
一、嚴(yán)格模式的使用
嚴(yán)格模式可以在腳本或函數(shù)級別實(shí)現(xiàn)。(即全局和局部模式)
1.全局
在js文件的最前面添加 "use strict"
2.局部
在函數(shù)內(nèi)部添加 "use strict",如下
function fn() { "use strict"; //some code}二、嚴(yán)格模式和非嚴(yán)格模式的對比
1.嚴(yán)格模式下,無法刪除(delete)變量(delete是不合格的標(biāo)識符))。非嚴(yán)格模式下會刪除失敗返回false
"use strict";var x;delete x;//報錯Delete of an unqualified identifier in strict mode.(不合格的標(biāo)識符)
2.嚴(yán)格模式中,函數(shù)形參存在同名的,拋出錯誤; 非嚴(yán)格模式不會
嚴(yán)格模式下
function fn(a,a){ "use strict"; result=a+a; console.log(result);}fn(2,4);//Duplicate parameter name not allowed in this context(重復(fù)的參數(shù)名稱在此上下文中不允許)非嚴(yán)格模式下
function fn1(a,a){ "use strict"; result=a+a; console.log(result);}fn1(2,4);//結(jié)果為83.嚴(yán)格模式不允許八進(jìn)制整數(shù)直接量(如下)。非嚴(yán)格模式下不會報錯。
"use strict"var x=089;console.log(x);//報錯:Decimals with leading zeros are not allowed in strict mode.
4.嚴(yán)格模式中,arguments對象是傳入函數(shù)內(nèi)實(shí)參列表的靜態(tài)副本(即不再追蹤參數(shù)的變化);非嚴(yán)格模式下,arguments對象里的元素和對應(yīng)的實(shí)參是指向同一個值的引用。
嚴(yán)格模式下
fn(5);function fn(a){ "use strict"; a = 42; // return a==arguments[0];//返回false console.log(a);//結(jié)果為42 console.log(arguments[0]);//結(jié)果為5,嚴(yán)格模式下arguments[0]表示這個調(diào)用方法的第一個參數(shù) (不再追蹤 參數(shù)的變化,在函數(shù)內(nèi)部,參數(shù)a被重新賦值為42,但arguments[0]仍然為5.)}非嚴(yán)格模式下
fn(5);function fn(a){ a = 42; // return a==arguments[0];//返回true console.log(a);//結(jié)果為42 console.log(arguments[0]);//結(jié)果為42(追蹤參數(shù)變化)}5.嚴(yán)格模式中 eval和arguments當(dāng)做關(guān)鍵字,它們不能被賦值和用作變量聲明
"use strict";var eval=3;//報錯:Unexpected eval or arguments in strict modevar argument=6;//同樣報錯
6.嚴(yán)格模式會限制對調(diào)用棧的檢測能力,訪問arguments.callee,arguments.callee.caller會拋出異常
嚴(yán)格模式下:
"use strict";function fn(n){ if(n==0){ return 1; }else{ return n*arguments.callee(n-1); }}console.log(fn(5));//報錯非嚴(yán)格模式下:
新聞熱點(diǎn)
疑難解答
圖片精選