在 JavaScript 中,'use strict';
表示代码应该在“严格模式”下执行。这使得编写良好且安全的 JS 代码更加容易。例如:
myVariable = 9;
在此,myVariable 在未声明的情况下被创建。在 JavaScript 中,这可以作为全局变量。但是,如果在严格模式下使用它,程序将抛出错误。例如:
'use strict';
// Error
myVariable = 9;
上面的代码会抛出错误,因为 myVariable 没有被声明。在严格模式下,您不能在未声明变量的情况下使用它们。
为了表明程序处于严格模式,我们使用了
'use strict';
在程序顶部。
您可以通过在程序开头添加 'use strict';
或 "use strict";
来声明严格模式。
当您在程序开头声明严格模式时,它将具有全局作用域,并且程序中的所有代码都将在严格模式下执行。
严格模式下的变量
在严格模式下,未使用声明就使用变量会抛出错误。
注意:您需要在程序开头声明严格模式。如果您在某些代码之后声明严格模式,它将不起作用。
例如,
console.log("some code");
// 'use strict' is ignored
// must be at the top
"use strict";
x = 21; // does not throw an error
函数中的严格模式
您也可以在函数内部使用严格模式。例如:
myVariable = 9;
console.log(myVariable); // 9
function hello() {
// applicable only for this function
'use strict';
string = 'hello'; // throws an error
}
hello();
如果您在函数内部使用 'use strict';
,则函数内的代码将处于严格模式。
在上面的程序中,'use strict';
用在了 hello()
函数内部。因此,严格模式仅适用于函数内部。
正如您所见,在程序开头,myVariable
在未声明的情况下被使用。
如果您在程序顶部声明 'use strict';
,那么您也不能在函数内部使用未声明的变量。例如:
// applicable to whole program
'use strict';
function hello() {
string = 'hello'; // throws an error
}
hello();
注意:严格模式不适用于带有 {}
块的语句。
严格模式下不允许的操作
1. 不允许使用未声明的变量。
'use strict';
a = 'hello'; // throws an error
2. 不允许使用未声明的对象。
'use strict';
person = {name: 'Carla', age: 25}; // throws an error
3. 不允许删除对象。
'use strict';
let person = {name: 'Carla'};
delete person; // throws an error
4. 不允许重复参数名。
"use strict";
function hello(p1, p1) { console.log('hello')}; // throws an error
hello();
5. 不允许赋值给不可写属性。
'use strict';
let obj1 = {};
Object.defineProperty(obj1, 'x', { value: 42, writable: false });
// assignment to a non-writable property
obj1.x = 9; // throws an error
6. 不允许赋值给只读属性。
'use strict';
let obj2 = { get x() { return 17; } };
// assignment to a getter-only property
obj2.x = 5; // throws an error
7. 不允许将属性赋值给不可扩展对象的新属性。
'use strict';
let obj = {};
Object.preventExtensions(obj);
// Assignment to a new property on a non-extensible object
obj.newValue = 'new value'; // throws an error
8. 不允许使用八进制语法。
'use strict';
let a = 010; // throws an error
9. 不允许使用变量名 arguments 和 eval。
'use strict';
let arguments = 'hello'; // throws an error
let eval = 44;
10.您也不能在严格模式下使用这些保留关键字。
implements
interface
let
package
private
protected
public
static
yield
严格模式的好处
使用严格模式
- 有助于编写更整洁的代码
- 将先前被接受的静默错误(错误语法)变为真实错误并抛出错误消息
- 使编写“安全”的 JavaScript 更加容易