javascript - ES6类字段箭头函数作用域问题

标签 javascript function this arrow-functions

我将箭头函数分配给外部变量。但我不明白为什么这是指“动物”构造函数。当我调用函数“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/

相关文章:

javascript - 如何修改此小书签以在选项卡而不是新窗口上工作?

javascript - Node simple-ssh 退出时没有错误

javascript - JavaScript 中 "decorator function"和 "decorator design pattern"有什么区别?

javascript - "this"关键字与多个对象

javascript - 在 JS 中使用这个还是新的?

javascript - 根据文本自动选择组合框中的值

javascript - React DropzoneComponent 在上传之前在本地打开/修改文件

javascript - 如何在不重新绑定(bind) this 的情况下返回带有粗箭头函数的对象?

php - 使用 MySql Update 和 PHP 制作表情符号

python - Python 中的平方根函数 - 它有什么问题?