JavaScript, why are you like this?

JavaScript have some weird quirks. And one of them is how pointer “this” works.

look at the code below:

var c = {
name: "this is c object",
log : function(){
this.name = "updated c object";
var setName = function(newname){
this.name = newname;
}
setName("Updating again! The c object");
console.log(this);
}
}

Look at the line 6, you might think that name has been set to value “Updating again! The c object”, because this is pointing to c object. BUT, if you run the code, you will find out that actually line 6, is creating new Global variable name, and setting it’s value to “Updating again! The c object”. This happens because of how the execution context is created in JavaScript. In JS, the interpreter will hoist all the variables and methods first. Meaning before real execution line 6 is interpreted and variable is set to global variable(sort of being pushed all the way up the code).

The solution would be to store the reference to c object then pass it.

 var c = {
name: "this is c object",
log : function(){
var self = this;
// note some developers use "that" instead of self
self.name = "updated c object";
var setName = function(newname){
self.name = newname;
}
setName("Updating again! The c object");
console.log(self);
}
} 

This way, we will not set the name to be global variable and it will be set to c object. So c.name will return “Updating again! The c object”

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s