es6 class类内部的方法自动开启了严格模式

-

今天看到react类组件内部的方法中this为undefined,原因是class类内部的方法,自动开启了局部严格模式,不是babel的问题

特此实验一下:

// 类内部的方法,自动开启了局部严格模式
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  speak() {
    console.log(this);
    console.log(`我的名字叫${this.name},年龄:${this.age}`);
  }
}
const p1 = new Person('小王', 18);
p1.speak(); // 正常读取到this
const x = p1.speak;
x() // 报错,this为undefined

function demo() {
  // 'use strict' // 局部开启严格模式后 this变成undefined,去掉严格模式后,this变成window
  console.log(this);
}

 

 

 

 

 

-

posted @ 2022-08-21 17:13  古墩古墩  Views(98)  Comments(0)    收藏  举报