我将箭头函数分配给外部变量。但我不明白为什么这是指“动物”构造函数。当我调用函数“fun”时,它打印了 “动物,真实的”。但我认为它会打印“Window,false”。
function Animal() {
this.sleep = () => {
console.log(this, this instanceof Animal)
}
}
let animal = new Animal();
animal.sleep(); // Animal, true
let fun = animal.sleep
fun = animal.sleep;
fun() // Animal, true -- why?
最佳答案
箭头函数解析this
lexically ,就像任何其他变量一样。这意味着 this
的值不取决于函数的调用方式,而是定义的方式/位置>.
sleep
函数在 Animal
构造函数中定义,通过 new
调用。因此 this
将引用 Animal
的新实例。
关于javascript - ES6类字段箭头函数作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57641371/