Javascript 'this' versus object name
By using this
you ensure that after changing your variable name e.g. from user
to something
your code still works.
Other than that, I imagine that (on some browsers) there may be some performance gain too, since with user.name
browser has to lookup in context outside your function while using this.name
sticks to current context.
Sample Code
var user = {
name : 'John Doe',
show_name : function(){
alert(user.name);
}
};
var something = user; // Passing the object to another variable
user = null; // Make the user variable point to something else
something.show_name();
If you run the code above, you'll hit an error at the following line:
alert(user.name); // <-- user is null, so this will produce the following Error:
Uncaught TypeError: Cannot read property 'name' of null
Now, if we switch to this
instead of user
, our code will work:
var user = {
name : 'John Doe',
show_name : function(){
alert(this.name);
}
};
var something = user; // Passing the object to another variable
user = null; // Make the user variable point to something else
something.show_name();
The above code will work since this
will point to the object that executed the show_name
function (this can be found in the left side of the . dot method notation and it's the object pointed to by something
).
REFERENCES:
To learn more about how the execution context (in our example the object) affects the this binding, read this excerpt from the wonderful book You Don't Know JS by Kyle Simpson.
The following chapters thoroughly explain how this
behaves in various contexts (but the whole series is worth reading!):
Chapter 1: this Or That?
Chapter 2: this All Makes Sense Now!
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.