在回调函数中理解“this”

时间:2020-12-21 01:52:58

标签: javascript callback this

我试图通过各种代码示例来理解“this”指的是什么。到目前为止,我知道“这个”取决于谁调用它或如何调用它。例如:

let user = {
  firstName: "Ilya",
  sayHi() {
    let arrow = () => console.log(this.firstName);
    arrow();
  },
  sayHi2() {
    let func = function() {
      console.log(this.firstName)
    }
    return func;
  }
};

user.sayHi(); // Ilya
let hi = user.sayHi; 
hi(); // undefined 
user.func = user.sayHi2()
user.func() // Ilya

上面的例子对我来说很有意义,我还了解到箭头函数没有 "this" 所以它通过它的外部词法环境搜索 "this"

现在,我正在尝试使用回调“这个”。

let user = {
  firstName: "Bob",
  sayHi(func) {
    func()
  }
}

function hello() {
  console.log("hello " + this.firstName);
}

user.sayHi(hello);
user.sayHi(()=>{ console.log("hello " + this.firstName)});

为什么 this.firstName 返回 undefined? “this” 不是指 user 对象,因为 sayHi() 是由 user 调用的吗?或者当函数作为回调执行时 "this" 值是否不同?

0 个答案:

没有答案
相关问题