Last active
May 30, 2016 10:31
-
-
Save jeserodz/45e3f093e46f6859f37b18657f667ffe to your computer and use it in GitHub Desktop.
JavaScript Examples: this Keyword
This file contains hidden or 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
// This script demonstrates the 4 rules for how the parameter 'this' works. | |
// 'this' is passed to each function at the moment it is invoked, and is a | |
// reference to the object that invokes the function. | |
// Let's define a function which returns the value of 'this' for its eventual | |
// context | |
var fn = function() { | |
return this; | |
}; | |
// Now we create an object with a property and an method referring to the function | |
var obj1 = { | |
fn1: fn, | |
name: "obj1" | |
}; | |
// We create another object with a property and a method referring to the same function | |
var obj2 = { | |
fn2: fn, | |
name: "obj2" | |
}; | |
// And a third object that doesn't refer to the function | |
var obj3 = { | |
fn3: function() {}, | |
name: "obj3" | |
}; | |
// Rule 1: If a function is NOT called as a method of an object, | |
// then the 'this' paramereter will be the global object | |
console.log(fn()); // -> 'this' == global | |
// Rule 2: If a function is called as a method of an object, then the 'this' | |
// parameter will be the object that contains the function | |
console.log(obj1.fn1()); // -> 'this' == obj1 | |
console.log(obj2.fn2()); // -> 'this' == obj2 | |
// Rule 3: If a function is called by the function method call(), then we | |
// can specify what the value of the parameter 'this' will be. This is handy | |
// for DRYness | |
console.log(fn.call(obj3)); | |
// Rule 4: If a function is called with the keyword 'new' in-front, then | |
// the parameter 'this' will be a completely new empty object. This feature is | |
// useful for creating 'constructor' functions, were we set pre-defined values | |
// on new objects we create | |
console.log(new fn()); | |
/* | |
The keyword this makes it possible for it to build just one function object | |
and use that as a method on a bunch of other objects. And every time you | |
call the method, it'll have access to whatever object it's being called on. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment