1

As far as I know about 'this' keyword:

  1. it by default refers to 'Window Obj'
  2. if it is written inside a function (being prop of an object), then it refers to the parent Obj

In the following example, as when foo.bar function is called (without help of call, apply, bind) then since the reference of obj (foo) is lost, so by default the new reference must be of window Obj.

Strangely, this keyword still returns an Object (which it always does) but of 3rd kind -- Arguments Object.

Also note, just 1 line above where calling arguments[0] (), 'this' on doing console.log returns our beloved 'window obj' only!

Now, from where the hell this new Object comes to picture and what is its importance?

According to my understanding (as reference of 'foo' is lost inside IIFE, the one should be of 'global window obj'). Kindly explain someone.

<script>
var foo = {
  bar: function() { 
    return this;
  }
};

var a = (function(){
  console.log(this);//returns window obj
  return arguments[0]();//here also should return window obj, as this here points to 'window obj'
})(foo.bar);

console.log("value of a:", a);

</script>
Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • 2
    "if it is written inside a function (being prop of an object), then it refers to the parent Obj" —`arguments[0]();` … `0` is the prop, `arguments` is the object, therefore `this` becomes `arguments`. – Quentin Feb 26 '19 at 07:40
  • thanks @Quentin - it helped! I never thought we itself are calling an object (special one - arguments premade) and we are simply calling it by property (0) which has got a function inside it (which will always point to the object holding it) :) – Deadpool Feb 26 '19 at 07:42

0 Answers0