0
const user = {
    name:'mdv',
    places : ['rio', 'new', 'aust'],
    printPlacesLived: function () {
        return this.places.map((place)=>this.name +'has lived in '+place)
    }
}

**this refers to the context in which they were created in ** (according to my knowledge)

2) so that is why inside my anonymous function this.name is working correctly

const user = {
    name:'mdv',
    places : ['rio', 'new', 'aust'],
    printPlacesLived:  () =>{
        return this.places.map((place)=>this.name +'has lived in '+place)
    }
}

Same method i have changed printPlacesLived to the arrow funtion so according to the defination

this refers to the context in which they were created in

1) Now i am getting places undefined if the definition is correct, printPlacesLived is created inside my user object so the refrence must be to places but not happening why ?

2) I am confused i studied some other definitions of arrow functions and this(it is mentioned that this retains the value of the enclosing lexical context's )

Now for printPlacesLived lexical context is name and places plese help me where did i go wrong

Teemu
  • 22,918
  • 7
  • 53
  • 106
lostcoder
  • 97
  • 10
  • Don't change your question totally after people have already answered it. Rather ask a new question. – Teemu Apr 17 '20 at 12:56
  • Sorry but now it makes more sense because i have tryed to keep my doubt in small code fomat – lostcoder Apr 17 '20 at 12:59
  • Like I said, please ask a new question. People have put their effort to the original question, and this edit totally changing the question invalidates the existing answer(s). – Teemu Apr 17 '20 at 13:00
  • ok but i don't know how to roll back – lostcoder Apr 17 '20 at 13:02
  • 1
    I can do it for you. You can find the versions by clicking the "edited" link below the question. – Teemu Apr 17 '20 at 13:02
  • let a = { thisScope : this, arrow : ()=> this } a.thisScope == a.arrow false plese explain why it returned false both are refreing to window object only – lostcoder Apr 17 '20 at 13:09

2 Answers2

0

Unlike regular functions, arrow functions do not have their own this. The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

let me = { 
 name: "Ashutosh Verma", 
 thisInArrow:() => { 
 console.log("My name is " + this.name); // no 'this' binding here 
 }, 
 thisInRegular(){ 
 console.log("My name is " + this.name); // 'this' binding works here 
 } 
};
me.thisInArrow(); 
me.thisInRegular();

enter image description here

Abdelrhman Arnos
  • 1,404
  • 3
  • 11
  • 22
-1
  1. Your 1 code is working good, need some corrections
  2. In arrow function This aims to level up