22nds
10/15/2017 - 10:43 PM

The different ways "this" is used in JavaScript

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