4

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()
Musa
  • 96,336
  • 17
  • 118
  • 137

3 Answers3

2

This should work:

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

obj.show();
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
husseinfawazbc
  • 301
  • 1
  • 2
  • 11
  • Sure It would work, But is there any other way to do that, not using any Function also. – ashutosh sarangi Nov 03 '20 at 17:57
  • I don't think so, to print out the ```name``` and ```age```, you will need to use ```console.log``` inside a function, since you cannot do so on its own, otherwise you can access the values outside the object like this: ```let obj = { name: 'Ashu', age: 123 } console.log(obj.name, obj.age)``` – husseinfawazbc Nov 03 '20 at 18:22
  • I Just trying out, what are another different approach would be apart from following Points. In Arrow Function. 1. Using call()/Apply()/Bind() 2. Using the Same Object inside the Functions. – ashutosh sarangi Nov 04 '20 at 03:51
2

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

  }
}

let obj = new Obj();
obj.show();
Saurav Kumar
  • 125
  • 1
  • 2
  • 10
1

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();
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53