class A {
getA() {
console.log(this);
}
}
let a = new A();
let funcA = a.getA;
funcA();//undefined
代码如上,是因为class么?我试了function A结果是window对象,为什么用class就会是undefined?难道funcA中的this不指向window?
求帮忙解答谢谢!
因为class xxx{}中的代码都是严格模式的。等于是自动加上"use strict"
在严格模式下禁止this指向全局对象(window)。
对的,因为你定义了一个 class 类 A,在它的方法中的 this 就是指当前对象。
希望问题描述更准确一些function A是哪个
首先正常来说 this 的指向的确是 window 对象,但是你定义了 class 之后 this 的指向就已经发生了转变,this 指向当前函数调用的对象也就是 A
一楼说的对,
因为class xxx{}中的代码都是严格模式的。等于是自动加上"use strict"
在严格模式下禁止this指向全局对象(window)。