3

I'm trying to understand what "this" refers through various code examples. So far, I know that "this" depends on who calls it or how it is called. For example:

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

The above example makes sense to me and I also learned that arrow functions do not have "this" so it searches for "this" through its outer lexical environments.

Now, I'm trying "this" using callbacks.

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

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

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

Why do this.firstName return undefined? Doesn't "this" refer to the user object since sayHi() is called by the user? Or does "this" value different when the function is executed as callbacks?

sangmin park
  • 547
  • 3
  • 7
  • 16
  • *"Doesn't "this" refer to the user"*. Arrow functions have no explicit `this` – charlietfl Dec 21 '20 at 01:56
  • Arrow functions uses this in its outer lexical environment. So doesn't that mean it this will reference the outer this of the sayHi() lexical environment? – sangmin park Dec 21 '20 at 02:03

0 Answers0