DEV Community

Discussion on: Reusable Code with "this" Keyword

Collapse
 
stereobooster profile image
stereobooster

I would avoid this keyword, because it is easy mess up things

let dog = {
    name: "Doug",
    breed: "pug",
    sayName: function() {return "The name of this dog is " + 
    this.name + "."}
}
let sayName = dog.sayName
sayName()
// "The name of this dog is 0.8151551794824166."
// To make it work you need
sayName.call(dog)
// or 
sayName.apply(dog)
Enter fullscreen mode Exit fullscreen mode

instead you can, for example, use closures:

const createDog = () => {
  const self = {
    name: "Doug",
    breed: "pug",
    sayName: () => `The name of this dog is ${self.name}.`
  }
  return self
}
Enter fullscreen mode Exit fullscreen mode