'use strict';
const s = 'Hi! I\'m a strict mode script!';
1.2 特定函数
为特定函数启用严格模式。
function myStrictFunction() {
// 函数级的严格模式
'use strict';
function nested() {
return 'And so am I!';
}
return `Hi! I'm a strict mode function! ${nested()}`;
}
function myNotStrictFunction() {
return 'I\'m not strict.';
}
'use strict';
mistypeVarible = 33; // ReferenceError: mistypeVarible is not defined
function f() {
a = 1; // ReferenceError: a is not defined
}
f();
console.log(this.a);
// non-strict mode 会创建一个全局变量
'use strict';
eval = ''; // SyntaxError: Unexpected eval or arguments in strict mode
arguments = []; // SyntaxError: Unexpected eval or arguments in strict mode
'use strict';
function add(a, b) {
arguments[0] = 11;
b = 22;
console.log(a, b);
return a + b;
}
add(1, 2);
// non-strict mode: 11 22
// strict mode: 1 22
'use strict';
// TypeError:
// 'caller', 'callee', and 'arguments' properties may not be accessed
// on strict mode functions or the arguments objects for calls to them
function fn() {
return arguments.callee;
}
fn();
'use strict';
function fn() {
console.log(this); // undefined
this.a = 1; // TypeError: Cannot set properties of undefined (setting 'a')
console.log(this.a); // TypeError: Cannot read properties of undefined (reading 'a')
}
fn(); // 等价于 fn.call();
eg3. 通过 call(), apply() 或 bind() 给函数指定特定的 this
'use strict';
function fn() {
this.a = 1;
console.log(this);
console.log(this.a);
}
const o = { a: 10, b: 11 };
fn.call(o);
// {a: 1, b: 11}
// 1
fn.call({});
// {a: 1}
// 1
fn.call(null);
// TypeError: Cannot set properties of null (setting 'a')
// null
// TypeError: Cannot read properties of null (reading 'a')
fn.call();
// TypeError: Cannot set properties of undefined (setting 'a')
// undefined
// TypeError: Cannot read properties of undefined (reading 'a')
2.5.2 函数栈不可追踪
当一个函数 fun 被调用时,fun.caller 表示最近调用 fun 的函数,fun.arguments 表示调用 fun 的参数。考虑到有些 ECMAScript 扩展会通过 fun.caller 和 fun.arguments 得到 JavaScript 的调用堆栈,所以严格模式中 fun.caller 和 fun.arguments 这两个属性都是不可删除的,在设置和检索时会报错。如下:
non-deletable properties, set or retrieved
function fn() {
'use strict';
// TypeError:
// 'caller', 'callee', and 'arguments' properties may not be accessed
// on strict mode functions or the arguments objects for calls to them
fn.caller;
fn.arguments;
}
function privilegedInvoker() {
return fn();
}
privilegedInvoker();