0

Below is the code , the code is working as expected if the function is usual function but it is not working with the arrow and anonymous function.But i am interested why it is not working so in case of arrow and anonymous function.

var testObj={
    name:"Shivendra",
    age:22,
    summary:function(){
        console.log(`His name is ${this.name} and he is ${this.age} years old {Summary}`)
    },
    summary2: ()=>{
        console.log(`His name is ${this.name} and he is ${this.age} years old {Summary2}`)
    },
    summary3:function(){
        var nestedAnonymousFunction=function(){
            console.log(`His name is ${this.name} and he is ${this.age} years old{Summary3} `)
        }
        nestedAnonymousFunction();
    }
}

testObj.summary();
testObj.summary2();
testObj.summary3();
AConsumer
  • 1,414
  • 1
  • 10
  • 24
  • Arrow functions is not just a short hand for functions. It binds current context to function. So, `this` will not point to object – Rajesh Nov 15 '18 at 05:06
  • 1
    `testObj.summary()` defines `this` because it is called as a method. `testObj.summary2()` treats `this` as any regular variable, so it closes over the value it has lexically, which is `window`. `testObj.summary3()` starts off with a correct binding to `this` because it is called as a method, then loses it when you call an anonymous non-method function (which assigns `this` to `window`). – Amadan Nov 15 '18 at 05:09
  • @Amadan if you can explain more then it would definitely help me – AConsumer Nov 15 '18 at 05:12
  • Also [good reading](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – Teemu Nov 15 '18 at 05:12
  • It has only been eight minutes since I closed with a duplicate link that has extensive explanations (and even exercises!) about this. I cannot believe you read through it already. If you have any _specific_ questions after going through that material, ask; but please don't ask me to repeat it when someone practically wrote a dissertation on the subject. (I added a short explanation to see how this relates to your particular question, but you have to read through the linked answers to understand what I said.) – Amadan Nov 15 '18 at 05:18

0 Answers0