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?