Skip to content

Instantly share code, notes, and snippets.

@AWaselnuk
Last active August 29, 2015 14:10
Show Gist options
  • Save AWaselnuk/5fca51214f920c2f46ac to your computer and use it in GitHub Desktop.
Save AWaselnuk/5fca51214f920c2f46ac to your computer and use it in GitHub Desktop.
Understanding 'this' in Javascript.
// 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