codecamp

严格模式(Strict mode)

严格模式开启检测和一些其他措施,使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

深入阅读

异常处理(Exception handling)
变量作用域和闭包(Variable scoping and closures)
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }