http://code.tutsplus.com/tutorials/fully-understanding-the-codethiscode-keyword–net-21117
note:
The Global Object
When a function is called without an owner object, the value of this becomes the global object.
In a web browser the global object is the browser window.
This example returns the window object as the value of this:
standalone Function (notice no new!)
1 2 3 4 5 6 7 8 |
var Person = function(name) { this.name = name || 'johndoe'; // 'this' refers to the window object }; var cody = Person('Cody Lindley'); //console.log(cody.name); // UNDEFINED! console.log(window.name); //logs Cody Lindley, |
The reason why window.name logs Cody Lindley is because the ‘this’ inside the function references the window global object. Hence when we attach the attribute name to this, it attaches name to the window object. the ‘this’ has nothing to do with the object Person.
new Object
Now, when we use new Object, we create an object on the heap, and this in our function refers to that object. IT IS NOT connected to the (global or window) object anymore
Hence, when we log cody.name, it works because cody is that object in the heap. The this in the function, refers to cody.
We assign name attribute to the object cody.
1 2 3 4 5 6 7 8 9 10 |
var Person = function(name) { this.name = name || 'johndoe'; // this will refer to the instanc ecreated }; var cody = new Person('Cody Lindley'); // create an instance, based on Person constructor console.log(cody.name); // logs 'Cody Lindley' console.log(window.name); //empty //Take note to use global.name if working with node JS. |
Also, take note that the this properties are public because there is no closure. If we create a closure (by creating inner functions), then the properties attached to this will then be private.
Another example:
1 2 3 4 5 6 7 8 9 10 11 12 |
var Person = function(name) { this.name = name || 'johndoe'; //public if no closure, private if closured var m_SSN = '12345678'; //private }; //create an object. the object's this is connected to global var cody = Person('Cody Lindley'); console.log(global.name); //logs Cody Lindley, //notice the new var cody2 = new Person('Cody Lindley'); console.log("name: " + cody2.name); |