Skip to content

Instantly share code, notes, and snippets.

@tekaratzas
Last active October 15, 2017 22:43
Show Gist options
  • Save tekaratzas/b5907aae8a8cd0af2f02803e29c7a14b to your computer and use it in GitHub Desktop.
Save tekaratzas/b5907aae8a8cd0af2f02803e29c7a14b to your computer and use it in GitHub Desktop.
The different ways "this" is used in JavaScript
// 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