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()
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()
use this syntax
const person ={
name: "anna",
hello () {
console.log(`hello ${this.name}!`)
}
}
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()