JS 严格模式下的常见规则大全(亲测有效)

1、全局变量显式声明

在正常模式中,如果一个变量没有声明就赋值,默认是全局变量。严格模式禁止这种用法,全局变量必须显式声明。

"use strict";
a = 1; // 报错,a is not defined

2、禁止this关键字指向全局对象

f();
function f(){
    console.log(!this); // false
} 
// 打印false,因为"this"指向全局对象,"!this"就是false
function f(){ 
  "use strict";
  console.log(this); // undefined
  console.log(!this); // true
} 
// 打印true,因为严格模式下,this的值为undefined,所以"!this"为true。

因此,使用构造函数时,如果忘了加new,this不再指向全局对象,而是报错。

f();
function f(){
  this.a = 1; //  this 指向的是 window
    console.log(this.a) // 1
};
function f(){
  "use strict"; // this未定义
  this.a = 1; //  Cannot set property 'a' of undefined
};

3、禁止删除变量

严格模式下无法删除变量。只有configurable设置为true的对象属性,才能被删除。

var x;
delete x;
console.log(x) // undefined

"use strict";
var x;      
delete x; 
// 语法错误
// 在严格模式下删除非限定标识符 (Delete of an unqualified identifier in strict mode.)
var o = Object.create(null, {'x': {
  value: 1,
  configurable: true
}});
delete o.x; // 删除成功
console.log(o.x) // undefined

4、函数不能有重名的参数

正常模式下,如果函数有多个重名的参数,可以用arguments[i]读取。严格模式下,这属于语法错误。

"use strict";
function f(a, a, b) { 
  
}
// 语法错误
// 此上下文中不允许重复的参数名 (Duplicate parameter name not allowed in this context)

更多严格模式的写法可以去 MDN文档 查看

猜你喜欢

转载自blog.csdn.net/lgysjfs/article/details/86527115