Last active
August 29, 2015 14:10
-
-
Save AWaselnuk/5fca51214f920c2f46ac to your computer and use it in GitHub Desktop.
Understanding 'this' in Javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Summary from http://www.sitepoint.com/what-is-this-in-javascript/ | |
//// GLOBAL SCOPE | |
// If there's no current object, 'this' refers to the global object | |
window.WhoAmI = "I'm the window object" | |
console.log(window.WhoAmI) // "I'm the window object" | |
console.log(this.WhoAmI) // "I'm the window object" | |
//// CALLING A FUNCTION | |
// 'This' remains the global object. Think of these functions as simply methods on the global object. | |
window.WhoAmI = "I'm the window object" | |
function testThis() { | |
console.log(this.WhoAmI); | |
} | |
testThis(); // "I'm the window object" | |
//// CALLING OBJECT METHODS | |
// When calling an object constructor or any of its methods, 'this' refers to the instance of the object. | |
window.WhoAmI = "I'm the window object" | |
function Test() { | |
this.WhoAmI = "I'm the test object"; | |
this.CheckThis1 = function() { | |
console.log(this.WhoAmI); | |
}; | |
} | |
Test.prototype.CheckThis2 = function() { | |
console.log(this.WhoAmI); | |
}; | |
var t = new Test(); // Note the 'new' keyword | |
console.log(t.WhoAmI); // "I'm the test object" | |
console.log(t.CheckThis1); // "I'm the test object" | |
console.log(t.CheckThis2); // "I'm the test object" | |
//// USING CALL OR APPLY | |
// These methods run javascript functions as if they were methods of another object. | |
function setType(type) { | |
this.WhoAmI = "I'm the " + type + " object"; | |
} | |
var A = {}; | |
setType.call(A, "A"); | |
console.log(A.WhoAmI); // "I'm the A object"; | |
var B = {}; | |
setType.apply(B, ["B"]); | |
console.log(B.WhoAmI); // "I'm the B object"; | |
/* | |
The only difference between 'call' and 'apply' is that 'call' expects a discrete number of parameters | |
while 'apply' expects an array of parameters | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment