詳解javascript中的Strict模式
在ES5中,引入了strict模式,我們可以稱之為嚴格模式。相應的sloppy mode就可以被稱為非嚴格模式。
嚴格模式并不是非嚴格模式的一個子集,相反的嚴格模式在語義上和非嚴格模式都發生了一定的變化,所以我們在使用過程中,一定要經過嚴格的測試。以保證在嚴格模式下程序的執行和非嚴格模式下的執行效果一致。
使用Strict modestrict mode會改變javascript的一些表現,我們將會在下一節中進行詳細的講解。
這里先來看一下,怎么使用strict mode。
Strict mode主要用在一個完整的腳本或者function中,并不適用于block {}。 如果在block中使用strict mode是不會生效的。
除此之外,eval中的代碼,Function代碼,event handler屬性和傳遞給WindowTimers.setTimeout()的string都可以看做是一個完整的腳本。我們可以在其中使用Strict mode。
如果是在script腳本中使用strict模式,可以直接在腳本的最上面加上'use strict':
// 整個腳本的strict模式’use strict’;var v = 'Hi! I’m a strict mode script!';
同樣的我們也可以在function中使用strict模式:
function strict() { // 函數的strict模式 ’use strict’; function nested() { return ’And so am I!’; } return 'Hi! I’m a strict mode function! ' + nested();}function notStrict() { return 'I’m not strict.'; }
如果使用的是ES6中引入的modules,那么modules中默認就已經是strict模式了,我們不需要再額外的使用'use strict':
function myModule() { // 默認就是strict模式}export default myModule;strict mode的新特性
strict mode在語法和運行時的表現上面和非嚴格模式都發生了一定的變化,接下來,我們一一來看。
強制拋出異常在js中,有很多情況下本來可能是錯誤的操作,但是因為語言特性的原因,并沒有拋出異常,從而導致最終運行結果并不是所期待的。
如果使用strict模式,則會直接拋出異常。
比如在strict模式中,不允許使用未定義的全局變量:
’use strict’;globalVar = 10; //ReferenceError: globalVar is not defined
這樣實際上可以避免手誤導致變量名字寫錯而導致的問題。
我再看一些其他的例子:
’use strict’;// 賦值給不可寫的全局變量,var undefined = 5; // throws a TypeErrorvar Infinity = 5; // throws a TypeError// 賦值給不可寫的屬性var obj1 = {};Object.defineProperty(obj1, ’x’, { value: 42, writable: false });obj1.x = 9; // throws a TypeError// 賦值給一個get方法var obj2 = { get x() { return 17; } };obj2.x = 5; // throws a TypeError// 賦值給一個禁止擴展的對象var fixed = {};Object.preventExtensions(fixed);fixed.newProp = ’ohai’; // throws a TypeError
Strict模式可以限制刪除不可刪除的屬性,比如構造函數的prototype:
’use strict’;delete Object.prototype; // throws a TypeError
禁止對象和函數參數中的重復屬性:
’use strict’;var o = { p: 1, p: 2 }; // Duplicate declarationfunction sum(a, a, c) { // Duplicate declaration ’use strict’; return a + a + c;}
禁止設置基礎類型的屬性:
(function() {’use strict’;false.true = ’’; // TypeError(14).sailing = ’home’; // TypeError’with’.you = ’far away’; // TypeError})();簡化變量的使用
使用Strict模式可以簡化變量的使用,讓程序代碼可讀性更強。
首先,strict模式禁止使用with。
with很強大,我們可以通過將對象傳遞給with,從而影響變量查找的scope chain。也就是說當我們在with block中需要使用到某個屬性的時候,除了在現有的scope chain中查找之外,還會在with傳遞的對象中查找。
with (expression) statement
使用with通常是為了簡化我們的代碼,比如:
var a, x, y;var r = 10;with (Math) { a = PI * r * r; x = r * cos(PI); y = r * sin(PI / 2);}
上面的例子中,PI是Math對象中的變量,但是我們可以在with block中直接使用。有點像java中的import的感覺。
下面的例子將會展示with在使用中的問題:
function f(x, o) { with (o) { console.log(x); }}
我們在with block中輸出x變量,從代碼可以看出f函數傳入了一個x變量。但是如果with使用的對象中如果也存在x屬性的話,就會出現意想不到的問題。
所以,在strict模式中,with是禁止使用的。
其次是對eval的改動。
傳統模式中,eval中定義的變量,將會自動被加入到包含eval的scope中。我們看個例子:
var x = 17;var evalX = eval('var x = 42; x;');console.log(x);
因為eval中引入了新的變量x,這個x的值將會覆蓋最開始定義的x=17. 最后我們得到結果是42.
如果加入use strict,eval中的變量將不會被加入到現有的Scope范圍中,我們將會得到結果17.
var x = 17;var evalX = eval('’use strict’; var x = 42; x;');console.log(x);
這樣做的好處是為了避免eval對現有程序邏輯的影響。
在strict模式下面,還不允許delete name:
’use strict’;var x;delete x; // !!! syntax erroreval(’var y; delete y;’); // !!! syntax error~~簡化arguments
在js中,arguments代表的是參數數組,首先在Strict模式下,arguments是不能作為變量名被賦值的:
’use strict’;arguments++;var obj = { set p(arguments) { } };try { } catch (arguments) { }function arguments() { }var f = new Function(’arguments’, '’use strict’; return 17;');
上面執行都會報錯。
另外,在普通模式下,arguments是和命名參數相綁定的,并且arguments[0]和arg同步變化,都表示的是第一個參數。
但是如果在strict模式下,arguments表示的是真正傳入的參數。
我們舉個例子:
function f(a) { a = 42; return [a, arguments[0]];}var pair = f(17);console.log(pair[0]); // 42console.log(pair[1]); // 42
上面的例子中,arguments[0]是和命名參數a綁定的,不管f傳入的是什么值,arguments[0]的值最后都是42.
如果換成strict模式:
function f(a) { ’use strict’; a = 42; return [a, arguments[0]];}var pair = f(17);console.log(pair[0]); // 42console.log(pair[1]); // 17
這個模式下arguments[0]接收的是實際傳入的參數,我們得到結果17.
在Strict模式下,arguments.callee是被禁用的。通常來說arguments.callee指向的是當前執行的函數,這會阻止虛擬機對內聯的優化,所以在Strict模式下是禁止的。
讓javascript變得更加安全在普通模式下,如果我們在一個函數f()中調用this,那么this指向的是全局對象。在strict模式下,這個this的值是undefined。
如果我們是通過call或者apply來調用的話,如果傳入的是primitive value(基礎類型),在普通模式下this會自動指向其box類(基礎類型對應的Object類型,比如Boolean,Number等等)。如果傳入的是undefined和null,那么this指向的是global Object。
而在strict模式下,this指向的是傳入的值,并不會做轉換或變形。
下面的值都是true:
’use strict’;function fun() { return this; }console.assert(fun() === undefined);console.assert(fun.call(2) === 2);console.assert(fun.apply(null) === null);console.assert(fun.call(undefined) === undefined);console.assert(fun.bind(true)() === true);
為什么會安全呢?這就意味著,在strict模式下,不能通過this來指向window對象,從而保證程序的安全性。
另外,在普通模式下,我們可以通過fun.caller或者fun.arguments來獲取到函數的調用者和參數,這有可能會訪問到一些private屬性或者不安全的變量,從而造成安全問題。
在strict模式下,fun.caller或者fun.arguments是禁止的。
function restricted() { ’use strict’; restricted.caller; // throws a TypeError restricted.arguments; // throws a TypeError}function privilegedInvoker() { return restricted();}privilegedInvoker();保留關鍵字和function的位置
為了保證JS標準的后續發展,在strict模式中,不允許使用關鍵字作為變量名,這些關鍵字包括implements, interface, let, package, private, protected, public, static 和 yield等。
function package(protected) { // !!! ’use strict’; var implements; // !!! interface: // !!! while (true) { break interface; // !!! } function private() { } // !!!}function fun(static) { ’use strict’; } // !!!
而對于function來說,在普通模式下,function是可以在任何位置的,在strict模式下,function的定義只能在腳本的頂層或者function內部定義:
’use strict’;if (true) { function f() { } // !!! syntax error f();}for (var i = 0; i < 5; i++) { function f2() { } // !!! syntax error f2();}function baz() { // kosher function eit() { } // also kosher}總結
Strict模式為JS的后續發展和現有編程模式的規范都起到了非常重要的作用。但是如果我們在瀏覽器端使用的話,還是需要注意瀏覽器的兼容性,并做好嚴格的測試。
以上就是詳解javascript中的Strict模式的詳細內容,更多關于javascript中的Strict模式的資料請關注好吧啦網其它相關文章!
相關文章: