I was trying to understand the lexical scoping of 'this' in arrow functions. I tried the following code -
const obj1 = {
name: "obj1name",
method: function(){
return () => {return this.name};
}
};
const arrowFunc1 = obj1.method();
console.log(arrowFunc1());
const obj2 = {
name: "obj2name",
method: function(){
return obj1.method();
}
};
const arrowFunc2 = obj2.method();
console.log(arrowFunc2());
This gives the output -
obj1name
obj1name
As expected, 'this' inside the arrow function was lexically scoped to obj1 and hence it prints 'obj1name' no matter how we call it. All fine till here. Then instead of defining obj2.method I decided to directly copy obj1.method into it -
const obj1 = {
name: "obj1name",
method: function(){
return () => {return this.name};
}
};
const arrowFunc1 = obj1.method();
console.log(arrowFunc1());
const obj2 = {
name: "obj2name",
method: obj1.method
};
const arrowFunc2 = obj2.method();
console.log(arrowFunc2());
This gives the output -
obj1name
obj2name
I don't understand why it prints 'obj2name'.
My understanding is that the arrow function is defined in obj1.method and so it is lexically scoped in it. Hence it should take the value of 'this' from obj1.method which is obj1.
What am i getting wrong?