0

how to bind this in a method that is an arrow function? Why person.hello.bind(person) doesn't work?

const person ={
  name: "anna",
  hello: ()=> console.log(`hello ${this.name}!`)
}


person.hello()
Anna
  • 19
  • 3
  • 8
    You cannot bind `this` in an arrow function. _Are there any solutions apart using the normal function_ - what's wrong with using a regular function? – Yousaf Sep 19 '20 at 14:51

2 Answers2

1

use this syntax

const person ={
  name: "anna",
  hello () {
    console.log(`hello ${this.name}!`)
  }
}
Dmitry Reutov
  • 2,995
  • 1
  • 5
  • 20
1

Arrow functions do not bind their own this, instead, they inherit the one from the parent scope, in your case, the this keyword is referencing the window object and you call only use regular functions. Or you can try other patterns like the "Revealing module pattern" which you implement like so:

function Person(name){
  this.name = name
  return {
    name: this.name,
    hello: () => console.log(`Hello ${this.name}!`)
  }
}
const Anna = Person('Anna')
Anna.hello()