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”