0

Can any one explain why arrow function is displaying "Ram" instead of 'Syam' ?

What I know that this in arrow function points parent object and normal function points global object but result is different here

this.name="Ram"
var name="Ajay"
var obj ={
    name:"Shyam",
    show : () => console.log(this.name),
    show2: function (){console.log(this.name)}
  }
obj.show() // Ram
obj.show2() // Shyam
Ashwani Panwar
  • 2,127
  • 3
  • 30
  • 45
  • 1
    _"What I know..."_ - You might want to have another look at how (arrow) functions work ;) – Andreas Nov 28 '19 at 12:03
  • be carefull by using global `name`: https://stackoverflow.com/questions/11064897/var-name-and-window-name – Nina Scholz Nov 28 '19 at 12:06
  • @Andreas can you please give a solution instead of commenting and closing question ? – Ashwani Panwar Nov 28 '19 at 12:11
  • @AshwaniPanwar hi, do you run your code in jsfiddle? – svltmccc Nov 28 '19 at 12:42
  • 1
    *"What I know that `this` in arrow function points parent object normal function points global object ..."* Not at all. `this` inside an arrow function is resolved *lexically*, just like any other variable. `this` inside "normal" functions depends on *how* the function is *called*. – Felix Kling Nov 28 '19 at 12:53
  • The links in the "it's a duplicate" box explain the behavior of `this`. Just read them. – Andreas Nov 28 '19 at 13:05

0 Answers0