DEV Community

Discussion on: Reusable Code with "this" Keyword

Collapse
 
willsmart profile image
willsmart • Edited

This kind of encapsulation is a great idea, but I strongly suggest getting an IDE setup that can tell you what type this has at the time you use it. I think it's one of the best reasons to use Typescript.

For example, in

function foo() {
  this.name = 'bob';
  const dog = {
    name: 'fluffy',
    fullName: `sir ${this.name}`,
    sayName: () => { spawn('say', [this.name]) },
    sendName: function() { send(this.name) }
  }
}
Enter fullscreen mode Exit fullscreen mode

it's pretty easy to accidentally miss that only name and sendName use the dog's name. both fullName and sayName will use "bob"

As you say, the reasons for this are a little out of scope, but getting a good IDE setup will catch this bug just as well as knowing why it happens, and is a must if you're going to use this in JS imo.

VSCode with Typescript (or just a good JS type inference setup) will put nice big red squigglies under the dodgy bits.