Javascript 'this' inside an object literal

javascript

Solution

When you return `name` from the method, it actually returns the `window.name` because there is not context involved.

When you call `this.name`, `this` points to the `dog` object which has a `name` property so it returns that.

Problem

I am new to javascript. I was doing some hands on "object literals". Below is the code i was trying. BodyLoaded is the event handler for onload event of body tag. //works - getName returns "bingo" ``` function BodyLoaded() { var dog = { name: "defaultname", getName: function () { return name; }, setName: function (n) { name = n; } }; dog.setName("bingo"); console.log(dog.getName()); } ``` //works too - getName returns "bingo" ``` function BodyLoaded() { var dog = { name: "defaultname", getName: function () { return this.name; }, setName: function (n) { this.name = n; } }; dog.setName("bingo"); console.log(dog.getName()); } ``` //doesnt work - getName returns "" ``` function BodyLoaded() { var dog = { name: "defaultname", getName: function () { return this.name; }, setName: function (n) { name = n; } }; dog.setName("bingo"); console.log(dog.getName()); } ``` The above code returns expected result when calling getName ("bingo"). But if I return this.name in the getName function, it returns and empty string. The strange part is, if i use this.name in both the functions (setName and getName) the code works fine and returns the expected value("bingo"). Trying to understand this behavior.

Original source

Related problems