1.了解你使用的JavaScript版本

2017-11-23  本文已影响0人  Somnusochi

1999年定稿的第3版ECMAScript标准(通常简称ES3),目前仍是最广泛采用的JavaScript版本。下一个有重大改进的标准是2009年发布的第5版,即ES5。

严格模式

ES5引入了另一个版本控制的考量——严格模式(strict mode)。此特性允许你选择在受限制的JavaScript版本中禁止使用一些JavaScript语言中问题较多或易于出错的特性。

使用方法

在程序的最开始增加一个特定的字符串字面量。

"use strict"

可以在函数体的开始处加入这句指令以启用该函数的严格模式

function f() {
 "use strict";
 // ...
}

旧的引擎不会进行任何的严格模式检查。如果你没有在ES5环境中做过测试,那么,编写的代码运行于ES5环境中就很容易出错。

function f(x) {
  "use strict";
  var arguments = []; //严格模式下,不允许重定义arguments变量
  // ...
}

use strict指令只有在脚本或函数的顶部才能生效。
下面有2个文件

// file1.js
"use strict"

function f() {
  // ...
}
// ...
// file2.js
// no strict-mode directive
function g() {
  var arguments = [];
  // ...
}
// ...

如果我们以file1.js文件开始,那么连接后的代码运行于严格模式下

// file1.js
"use strict"

function f() {
  // ...
}
// ...
// file2.js
// no strict-mode directive
function g() {
  var arguments = [];//严格模式下,不允许重定义arguments变量
  // ...
}
// ...

如果我们以file2.js文件开始,那么连接后的代码运行于非严格模式下:

// file2.js
// no strict-mode directive
function g() {
  var arguments = [];
  // ...
}
// ...
// file1.js
"use strict"

function f() { //no longer strict
  // ...
}
// ...

所以当编写健壮的代码应对各种各样的代码连接,有两个可选方案:

(function() {
  "use strict";

  function f() {
    // ...
  }
  // ...
})();

提示

上一篇 下一篇

猜你喜欢

热点阅读