当我尝试通过两个函数访问全局变量时,我对此表示怀疑。一个功能是箭头功能,另一个功能是普通功能。箭头功能可以正常工作,但普通功能无法打印全局变量。为什么?
示例代码
class Data1{
constructor(m1){
this.m1 = m1
}
}
class Data2 extends Data1{
func1(){
console.log(this.m1)
this.m1 = 20
}
func2=()=>{
console.log(this.m1)
this.m1 = 40
}
}
d1 = new Data1(10)
d2 = new Data2()
d2.func1()
d2.func2()
输出
undefined
20
在常规函数中,此关键字代表调用函数的对象,可以是窗口,文档,按钮或其他。
使用箭头功能,此关键字始终代表定义箭头功能的对象。
如果您在Data1中编写构造函数并将func1绑定到Data1对象,它将起作用。例如。
constructor(){
this.func1 = this.func1.bind(this);
}
在线:
d2 = new Data2()
您正在调用不带任何参数的Data1的构造函数。 m1将是不确定的。您将需要将一个参数传递给Data1的构造函数。通过将参数传递给Data2可以自动完成此操作。
d2 = new Data2(10);
这应该可以解决您的问题。
结果与功能范围(箭头功能)无关,甚至与this绑定无关。