Javascript 'this' inside an object literal
<p>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.</p>

<p>//works - getName returns "bingo"</p>

<pre><code>function BodyLoaded()
{
    var dog = {

        name: "defaultname",
        getName: function () {
            return name;
        },
        setName: function (n) {
            name = n;
        }
    };

    dog.setName("bingo");
    console.log(dog.getName());
}
</code></pre>

<p>//works too - getName returns "bingo"</p>

<pre><code>function BodyLoaded()
{
    var dog = {

        name: "defaultname",
        getName: function () {
            return this.name;
        },
        setName: function (n) {
            this.name = n;
        }
    };

    dog.setName("bingo");
    console.log(dog.getName());
}
</code></pre>

<p>//doesnt work - getName returns ""</p>

<pre><code>function BodyLoaded()
{
    var dog = {

        name: "defaultname",
        getName: function () {
            return this.name;
        },
        setName: function (n) {
            name = n;
        }
    };

    dog.setName("bingo");
    console.log(dog.getName());
}
</code></pre>

<p>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.</p>
