0

I am new to Javascript, please help me in understanding the significance of "this" keyword. I have added comments in front of each console.log() statements in below code snippet, these are my questions/doubts.

This is my code :

var parentObj = {
aa : 87,
bb : 11,
childObj :  {
    a : 12,
    b : 1122,
    fun1 : function(){console.log(this)},   // this is method() so here "this" will point to our "childObj"
    fun2 : ()=>{console.log(this)},        //this Fat Arrow function is pointing to "window(global)" object why? 
    fun3 : function(){  
        var innerFunc1 = ()=>{ console.log(this)}  // this Fat Arrow function is pointing to "childObj" object why?
        innerFunc1();

        function innerFunc2(){console.log(this)}  // this regular function is pointing to "window(global)" object why? 
        innerFunc2()
    }       
}
}

parentObj.childObj.fun1();
parentObj.childObj.fun2();
parentObj.childObj.fun3();

This is the OutPut I am getting :

enter image description here

Rahul Singh
  • 164
  • 6
  • 2
    An arrow function's `this` inherits from the outer scope. In non-strict mode, `this` on the top level is `window`, which explains `fun2`. A `function`'s `this` is taken from its calling context (the object on which the function was called, if any). `innerFunc2` is called with no calling context, so `this` is the global object. For `fun1` and `fun3`, `this` refers to the `childObj` because that's the object on which the function was called – CertainPerformance Feb 28 '20 at 07:14
  • Thanks, @CertainPerformance This was really helpful. – Rahul Singh Feb 28 '20 at 09:22

0 Answers0