"use strict" // Assignment to NaN NaN = 'a'; // TypeError: Cannot assign to read noly property 'NaN' of #<Object> // Assignment to a non-writable property var obj1 = {}; Object.defineProperty(obj1, "x", { value: 42, writable: false }); obj1.x = 9; // throws a TypeError // Assignment to a getter-only property var obj2 = { get x() { return 18; } }; obj2.x = 5; // throws a TypeError // Assignment to a new property on a non-extensible object var fixed = {}; Object.preventExtensions(fixed); fixed.newProp = "ohai"; // throws a TypeError
(3)
严格模式禁止删除一个声明为不可删除的属性。
1 2
"use strict"; delete Object.prototype; // throws a TypeError
(4)
严格模式禁止声明重名属性。
1 2 3 4 5
"use strict"; var o = { p: 1, p: 2 }; // !!! syntax error
"use strict"; eval = 18; arguments++; ++eval; var obj = { set p(arguments) { } }; var eval; try { } catch(arguments) { } function x(eval) { } function arguments() { } var y = function eval() { }; var f = new Function("arguments", "'use strict'; return 18;");
(2)
在严格模式下,修改函数参数不会影响arguments,下面的示例代码能够正常运行。
1 2 3 4 5 6 7 8
function f(a) { "use strict"; a = 42; return [a, arguments[0]]; } var pair = f(18); console.assert(pair[0] === 42); console.assert(pair[1] === 18);
"use strict"; function f(a) { console.log(this); } f.call(null); f();
结果为:
1 2
null undefined
(2)
严格模式禁止访问函数对象属性caller和arguments,这意味着不再可能遍历调用堆栈了。
1 2 3 4 5 6 7 8 9 10 11 12
"use strict"; function outer() { inner(); } function inner() { console.log(arguments.callee.caller); // TypeError: 'caller', 'callee', and // 'arguments' properties may not be accessed // on strict mode functions or the arguments // objects for calls to them } outer();