严格模式(Strict mode)

2018-06-15 18:44 更新

严格模式开启检测和一些其他措施,使JavaScript变成更整洁的语言。推荐使用严格模式。为了开启严格模式,只需在JavaScript文件或script标签第一行添加如下语句:

'use strict';

你也可以在每个函数上选择性开启严格模式,只需将上面的代码放在函数的开头:

function functionInStrictMode() {
    'use strict';
}

下面的两小节看下严格模式的三大好处。

明确错误(Explicit errors)

让我们看一个例子,严格模式给我们明确的错误,否则JavaScript总是静默失败:下面的函数 f() 执行一些非法操作,它试图更改所有字符串都有的只读属性——length:

function f() {
    'abc'.length = 5;
}

当你调用上面的函数,它静默失败,赋值操作被简单忽略。让我们将 f() 在严格模式下运行:

function f_strict() {
    'use strict';
    'abc'.length = 5;
}

现在浏览器报给我们一些错误:

> f_strict()
TypeError: Cannot assign to read only property 'length' of abc

不是方法的函数中的this(this in non-method functions)

在严格模式下,不作为方法的函数中的this值是undefined:

function f_strict() {
    'use strict';
    return this;
}
console.log(f_strict() === undefined);  // true

在非严格模式下,this的值是被称作全局对象(global object)(在浏览器里是window):

function f() {
    return this;
}
console.log(f() === window);  // true

不再自动创建全局变量(No auto-created global variables) 在非严格模式下,如果你给不存在的变量赋值,JavaScript会自动创建一个全局变量:

> function f() { foo = 5 }
> f()  // 不会报错
> foo
5

在严格模式下,这会产生一个错误:

> function f_strict() { 'use strict'; foo2 = 4; }
> f_strict()
ReferenceError: foo2 is not defined

深入阅读

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号