I'm struggling with "this" keyword in JS. I've listed 3 different cases that I'm confusing with.
const person = {
name: "joe",
talk(){
this.foo(function (){
console.log(this);
});
},
foo(a) {
a()
}
};
person.talk();
In the first scenario: despite foo is a member of person object; when I call foo function it returns me a window object reference.
const person = {
name: "joe",
talk(){
foo(function (){
console.log(this);
});
},
};
function foo(a){
a()
}
person.talk();
In the second scenario: there is nothing changed, though I put foo function outside of person object.
But if I change the way of defining the callback function within foo function with Arrow notation as follows:
const person = {
name: "joe",
talk(){
foo(() => {
console.log(this);
});
},
};
function foo(a){
a()
}
person.talk();
Then this time, the first scenario and the second scenario that I mentioned above print out the reference of person object regardless whether foo is defined within person object or not.
What is the basis of those results?