forked from shiiiiiiji/IFEEES
-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
use strict 的位置
use strict 可以放在整个脚本最前面,整个脚本都是严格模式,或函数体最前面,函数体内是严格模式。前面只能是空行或注释,否则无效
let x = 1;
'use strict'; // 放在这里无效
function fn (a, a) {
}
严格模式的影响
禁止 this 指向全局对象
| 非严格模式 | 严格模式 | |
|---|---|---|
| ES6 Module | undefined | |
| CommonJS Module | global 对象 | undefined |
| 浏览器(Chorme) | window 对象 | undefined |
不能删除声明的变量(函数、类)
'use strict';
const x = 1;
// SyntaxError: Delete of an unqualified identifier in strict mode.
delete x;
不能使用 with 语句
'use strict';
const x = {
a: 'a',
b: 'b'
};
// SyntaxError: Strict mode code may not include a with statement
with (x) {
console.log(a);
}
eval 会形成自己的局部作用域
'use strict';
var x = 1;
eval("var x = 2; console.log(x);");
console.log(x); // 1,非严格模式下是 2
eval 不能被重新赋值
'use strict';
// SyntaxError: Unexpected eval or arguments in strict mode
// 非严格模式可以赋值成功
eval = 1;
禁止八进制表示法
'use strict';
// SyntaxError: Octal literals are not allowed in strict mode.
const x = 0123;
不能对只读属性赋值
'use strict';
const x = {};
Object.defineProperty(x, 'a', {
value: 1,
writable: false,
enumerable: true,
configurable: true
});
// TypeError: Cannot assign to read only property 'a' of object '#<Object>'
x.a = 2;
不能删除不可删除的属性
'use strict';
const x = {};
Object.defineProperty(x, 'a', {
value: 1,
writable: false,
enumerable: true,
configurable: false
});
// TypeError: Cannot delete property 'a' of #<Object>
delete x.a;
函数参数不能重名
'use strict';
// SyntaxError: Duplicate parameter name not allowed in this context
function fn (a, a) {
}
arguments 不能被重新赋值
'use strict';
function x () {
// SyntaxError: Unexpected eval or arguments in strict mode
// 非严格模式可以赋值成功
arguments = 1;
console.log(arguments)
}
x();
arguments 不再追踪参数的变化
'use strict';
function x (m) {
m = 2;
// 2 [Arguments] { '0': 1 }
// 非严格模式是 2 [Arguments] { '0': 2 }
console.log(m, arguments);
}
x(1);
不能使用 arguments.callee
'use strict';
function x () {
y(1);
}
function y (a) {
// TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
console.log(arguments.callee);
}
x();
不能使用 函数.caller 和 函数.arguments
'use strict';
function x () {
y(1);
}
function y (a) {
// TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
console.log(y.arguments, y.caller);
}
x();
参考
1.http://es6.ruanyifeng.com/#docs/module#严格模式
2.http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html
Reactions are currently unavailable