Javascript 'this' versus object name

javascript, object, this

Solution

The difference becomes obvious, if you have a look at this example. It creates a second object and sets the prototype accordingly.

var user = {

    name : 'John Doe',

    show_name : function(){

        alert(this.name);

        // OR

        alert(user.name);
    }
};

user2 = Object.create( user );
user2.name = "someone else";

user2.show_name();

Here `this.name` refers to the current object's `name` property, whereas `user.name` always refers to the original `name` property.

Problem

A question spurred by curiosity, if I have the following code, what's the benefit (beyond just the simplicity) of calling a property via `this` instead of `user` in the `show_name` method? ``` var user = { name : 'John Doe', show_name : function(){ alert(this.name); // OR alert(user.name); } }; ```

Original source

Related problems