5

为什么这段代码很好:

var test = {
    fn1: function(_origin, _componentType) {
        if(arguments.length > 1) throw "xx";
        // this strict is ok
        "use strict";

        var interface               = new Object(this);
    }
}

虽然这不是

var test = {
    fn1: function(_origin, _componentType) {
        // This strict throws SyntaxError
        "use strict";

        if(arguments.length > 1) throw "xx";
        var interface               = new Object(this);
    }
}

我知道 interface 在严格模式下是保留字,但是两个示例都不应该抛出错误吗?

4

2 回答 2

10

"use strict";需要是函数(或脚本,如果是脚本范围)中的第一条语句以触发严格模式;在其他任何地方,你也可以在写作"merry christmas";

于 2015-11-09T07:52:27.907 回答
4

第一个示例实际上并未启用严格模式。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Invoking_strict_mode

严格模式适用于整个脚本单个函数。它不适用于包含在 {} 大括号中的块语句;试图将它应用到这样的上下文中没有任何作用。

于 2015-11-09T07:52:43.307 回答