this keyword in Objects Javascript
this Keyword in Objects Javascript
-
In a traditional function in an object
let user = { name: "Chaitanya", age: 22, getDetails() { console.log(this.name); // here `this` will point to the object user = { name: "Chaitanya", age: 22, getDetails: getDetails() } }, } user.getDetails(); // Chaitanya -
In a traditional function in a nested object
let user = { name: "Chaitanya", age: 22, childObj: { newName: "Shahare", getDetails() { console.log(this.newName, "and", this.name); // here this will point to the `childObj` { newName: "Shahare", getDetails() } }, }, } user.childObj.getDetails(); // Shahare and undefined -
In an arrow function in an object
let user = { name: "Chaitanya", age: 22, getDetails: () => { console.log(this); // here `this` refers to the global/window object }, } user.getDetails(); // {} -
In an arrow function in a function in an object (obj > traditional function > arrow function)
let user = { name: "Chaitanya", age: 22, getDetails() { const nestedArrow = () => console.log(this.name); // `this` refers to the parent's `this` which is `user` object nestedArrow(); }, } user.getDetails(); // Chaitanya