1

I have Used this keyword in Java Script many times but One thing that confuses me is how the this keyword works. Put simply, this is a referencing alias—it’s just knowing what exactly it references. I didn't get clear understanding of how this works.

For Example The code sample below

  var car = 'swift';

var myCar = {car: 'Honda city'};

var getCar = function() {
  console.log(this.car);
};

myCar.getCar = getCar;
myCar.getCar();

// output: Honda City
getCar();

// output: swift
Tharif
  • 13,172
  • 9
  • 51
  • 73
Subhash Chandra
  • 2,817
  • 24
  • 28
  • there's loads of answers here already, but put simply, it has whatever object was on the left of the function call, i.e `obj` in `obj.func()` _at the time the function was called_. An alias to a function called as just `func()` will have the default `this` value of `window`, or `null` (depending on "strict mode"). There's then exceptions to this for functions called via `.bind`, `.call` or `.apply`. – Alnitak Oct 31 '15 at 07:00
  • You can watch [YouTube - Tutorial](https://www.youtube.com/watch?v=fjJoX9F_F5g&list=PLoYCgNOIyGABI011EYc-avPOsk1YsMUe_&index=5). But to put it simple words, `this` represunts current object.So when you do `myCar.getCar()` current object is *myCar* but when you do `getCar()`, as mentioned be @Alnitak, since there is no object in LHS, default object is window. – Rajesh Oct 31 '15 at 07:09
  • 1
    @subhash for clarity of this keyword in javascript you can simply read this post from stackoverflow: http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Dawlatzai Ghousi Oct 31 '15 at 07:11

0 Answers0