-2
let object = {
    name : "Aditya",
    age : 20,
    printIt : function(){
        console.log(this.name + " " + this.age)
    }
}

in above object i want to change printIt function in to an arrow function i tried as below but it is not working.

let object = {
    name : "Aditya",
    age : 20,
    printIt =  () => {
        console.log(this.name + " " + this.age)
    }
}

how can we change the printIt function to arrow function in side this object

kichu
  • 121
  • 1
  • 1
  • 11
  • 2
    Be aware that the context of `this` inside an arrow function is different. More info here: [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions) – Reyno Nov 10 '21 at 08:20
  • 1
    If you just want a shorter syntax, there is one that happens to be the most appropriate syntax for this use case, aynway: [method definitions](//developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Method_definitions). – Sebastian Simon Nov 10 '21 at 08:30

1 Answers1

0

Use a colon : like in name and age.

let object = {
      name: "Aditya",
      age: 20,
      printIt: () => {
          console.log(this.name + " " + this.age)
      }
  }
 
object.printIt();

Altough because of the arrow function, this doens't work like you expect it to. Simply use the traditional function syntax and the this will work like expected.

let otherObject = {
      name: "Aditya",
      age: 20,
      printIt: function() {
          console.log(this.name + " " + this.age)
      }
  }
  
otherObject.printIt();

Another solution would be to call object.name and object.age within the printIt function of the first code example, but that's not best practice as the arrow function has to be changed when you rename the object.

Jelle
  • 758
  • 2
  • 14
  • 36