Last active
October 15, 2017 22:43
-
-
Save tekaratzas/b5907aae8a8cd0af2f02803e29c7a14b to your computer and use it in GitHub Desktop.
The different ways "this" is used in JavaScript
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
// 1 | |
console.log(this); // refers to the Global Object aka window | |
// its methods include prompt alert confirm etc... | |
// 2 | |
function test() { | |
console.log(this); | |
this.method = function inner() {console.log(this)}; | |
}; // Here again "this" will refer to the global object | |
test(); | |
//3 | |
var obj = new test(); // Since we are using the constructor, this now refers to the new object "test"! | |
//4 | |
obj.method(); //infereing methods forced this to be set to its object | |
// 5: You can also force this to be a certain value using call or apply | |
function foo(a, b, c) { | |
this.a = a; | |
this.b = b; | |
this.c = c; | |
} | |
var bar = {}; | |
foo.apply(bar, [1, 2, 3]); //this first parameter will be what "this" is | |
console.log(bar) // bar will be an arry like a: 1, b: 2, c: 3 | |
foo.call(bar, 4, 5, 6); // same here | |
console.log(bar) // bar will be an arry like a: 4, b: 5, c: 6 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment