How to Get values inside Arrow function

Viewed 770

How to Get values inside Arrow function, which is Inside an Object.

I want to access other properties of that Object.

let obj = {
  name:'Ashu',
  age:123,
  show: ()=>{
    // I want to print Name and Age how to do that
    // Is there any other way to do get Name and Age Property
    // I don't want to replace the Arrow function
      console.log(obj.name, obj.age);
  }
}
obj.show()

3 Answers

This should work:

let obj = {
    name: 'Ashu',
    age: 123,
    show: () => {
        console.log(obj.name, obj.age);
    }
}

obj.show();

Arrow functions don't capture current this, for capturing this you need to write a regular function.

let obj = {
    name:'Ashu',
    age:123,
    show: function() {
        console.log(this.name, this.age);
    }
};

obj.show();

class Obj {
  constructor(){
    this.name ='Ansh';
    this.age = 123;
    this.show = () => {
        console.log(this.name, this.age);
      }

  }
}

let obj = new Obj();
obj.show();

Related