为什么这个代码很好:
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);
}
}
我知道接口在严格模式下是保留字,但这两个例子不应该都抛出错误吗?
"use strict";
需要是函数中(或脚本中,如果是脚本范围)的第一条语句才能触发严格模式;在其他任何地方,您都可以编写"merry christmas";
。
第一个例子实际上并没有启用严格模式。看见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Invoking_strict_mode:
严格模式适用于整个脚本或单个函数。它不适用于用{}大括号括起来的块语句;试图把它应用到这样的环境中是无济于事的。