ES6 class 字段箭头函数作用域问题
ES6 class field arrow functions scoping problem
我将我的箭头函数分配给了外部 variable.But 我不明白为什么这是指 'Animal' 构造函数。当我调用函数 'fun' 时,它打印出来
'Animal, true'。但我认为它会打印 '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
的值 而不是 取决于函数的调用方式 ,但 how/where 它是 已定义.
sleep
函数定义在Animal
构造函数内部,用new
调用。因此 this
将引用 Animal
.
的新实例
我将我的箭头函数分配给了外部 variable.But 我不明白为什么这是指 'Animal' 构造函数。当我调用函数 'fun' 时,它打印出来 'Animal, true'。但我认为它会打印 '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
的值 而不是 取决于函数的调用方式 ,但 how/where 它是 已定义.
sleep
函数定义在Animal
构造函数内部,用new
调用。因此 this
将引用 Animal
.