'use strict';
指出应以" 严格模式"执行JavaScript代码。这使得编写良好且安全的JavaScript代码更加容易。例如,
myVariable = 9;
在这里,创建 myVariable 时无需声明。在JavaScript中,它可以作为全局变量使用。但是,如果在严格模式下使用此程序,则程序将引发错误。例如,
'use strict';
// Error
myVariable = 9;
上面的代码引发错误,因为未声明 myVariable 。在严格模式下,必须先声明变量才能使用变量。
为了表明该程序处于严格模式下,无涯教程使用了
'use strict';
在程序的顶部。
您可以通过在程序的开头添加'use strict';
或"use strict";
来声明严格模式。
当您在程序的开头声明严格模式时,它将具有全局作用域,并且程序中的所有代码都将以严格模式执行。
在严格模式下,使用变量而不声明它会引发错误。
注意:您需要在程序的顶部中声明严格模式。如果您在某些代码下声明了严格模式,则该模式将无效。
例如,
console.log("some code");
// 'use strict' 被忽略必须在顶部
"use strict";
x = 21;//不抛出错误
您还可以在函数内部使用严格模式。例如,
myVariable = 9;
console.log(myVariable);//9
function hello() {
//仅适用于此功能
'use strict';
string = 'hello';//throws an error
}
hello();
如果在函数内部使用'use strict';
,则函数内部的代码将处于严格模式。
在上面的程序中,在 hello()
函数内部使用了'use strict';
。因此,严格模式仅适用于函数内部。
如您所见,在程序的开头,使用了 myVariable
而不进行声明。
如果您声明'use strict';
在程序顶部,也不能在未在函数内部声明变量的情况下使用变量。例如,
// 适用于整个程序
'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. 不允许分配给仅使用getter的属性。
'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. 不允许使用变量名称参数和eval。
'use strict';
let arguments = 'hello';//throws an error
let eval = 44;
10. 也不能在严格模式下使用这些保留的关键字。
implements
interface
let
package
private
protected
public
static
yield
使用严格模式:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
HarmonyOS快速入门与实战 -〔QCon+案例研习社〕