'use strict'-->校验js

// file.js
"use strict"
function doStuff(){
    // use strict is enabled here!
}
这样佻的file.js都会应用上"use strict"模式。
如果你仅想在一个函数中使用:

// file.js
function a(){
    "use strict";
    // use strict is enabled in this context
    function nestedFunction(){
        // and here too
    }
}
好处
检查对象中的重复键

var zombie = {
    eyeLeft : 0,
    eyeRight: 1,
    // ... a lot of keys ...
    eyeLeft : 1
}

这段代码会抛出一个错误因为 eyeLeft 出现了两次。这比你用眼睛去找错误要快多了。

未声明变量

plane = 5;
你现在已经知道忘记在这个变量前面加var了。不过如果你不知道,调试起来是非常痛苦的,因为这个变量是声明在全局上下文(global context)中的,而且可能被其他地方改掉。想象一下,如果你声明了一个全局的 i, 在嵌套循环中可能会引起混乱。

重复的参数

function run(fromWhom, fromWhom){}
注意fromWho出现了两次,因此会抛出一个错误。

限制函数中的arguments

var run = function(fromWhom){
    arguments[0] = 'alien';
    alert(fromWhom);
}
run('zombie');
// alert: 'alien';
现在你可以使用"use strict"

var run = function(fromWhom){
    "use strict";
    arguments[0] = 'alien';
    alert(fromWhom);
}
run('zombie');
// alert: 'zombie';
arguments[0] = 'alien' 改变了参数fromWhom,use strict 又节约了你的时间。

转载:http://ourjs.com/detail/52f572bf4534c0d806000024

猜你喜欢

转载自blog.csdn.net/zhanjianjiu/article/details/78474775
今日推荐