I am trying to understand this piece of code and having hard time with it -
const obj = {
name: "Cristiano",
lname: "Ronaldo",
getName: function () {
function another() {
console.log(this);
}
another();
},
};
obj.getName();
The console logs to the Window
object which is quite confusing.
Any ideas as to why?
Secondly, this is the way I am interpreting such questions -
In case of function declarations (statements), the this
object refers to the - just immediate parent object. If it's a function then the this
binding to the same function and so on.
In case of ES6 arrow functions, the this
object refers to the - The this
binding of parent normal function declaration.
That's the reason why -
const obj = {
name: "Cristiano",
lname: "Ronaldo",
moreObj: {
name: "Siiii",
getName: function () {
const named = () => this.name;
console.log(named());
},
},
};
obj.moreObj.getName();
returns Siiii
as log.
Am I understanding it right?
Thanks in advance :)