天天看點

javascript中的Strict模式簡介使用Strict modestrict mode的新特性簡化變量的使用簡化arguments讓javascript變得更加安全保留關鍵字和function的位置總結

簡介

我們都知道javascript是一個弱類型語言,在ES5之前,javascript的程式編寫具有很強的随意性,我可以稱之為懶散模式(sloppy mode)。比如可以使用未定義的變量,可以給對象中的任意屬性指派并不會抛出異常等等。

在ES5中,引入了strict模式,我們可以稱之為嚴格模式。相應的sloppy mode就可以被稱為非嚴格模式。

嚴格模式并不是非嚴格模式的一個子集,相反的嚴格模式在語義上和非嚴格模式都發生了一定的變化,是以我們在使用過程中,一定要經過嚴格的測試。以保證在嚴格模式下程式的執行和非嚴格模式下的執行效果一緻。

使用Strict mode

strict 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 TypeError
var 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 declaration
function 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 error
eval('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]);  // 42
console.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]); // 42
console.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的後續發展和現有程式設計模式的規範都起到了非常重要的作用。但是如果我們在浏覽器端使用的話,還是需要注意浏覽器的相容性,并做好嚴格的測試。

本文作者:flydean程式那些事

本文連結:

http://www.flydean.com/js-use-strict/

本文來源:flydean的部落格

歡迎關注我的公衆号:「程式那些事」最通俗的解讀,最深刻的幹貨,最簡潔的教程,衆多你不知道的小技巧等你來發現!