DEV Community

Discussion on: Rethinking JavaScript: The complete elimination and eradication of JavaScript's this.

 
joelnet profile image
JavaScript Joel • Edited

TypeScript doesn't fix all this issues.

If you check out the REPL at typescriptlang.org/play/ and enter this code:

const cat = {
    sound: 'meow',
    speak() { return this.sound }
}

const speak = cat.speak
speak()

You'll find it still has problems with this.

My solution to avoiding this is to write JavaScript functionally and not to mix data and functions together into classes.

I would instead write the above like this:

const cat = {
  sound: 'meow',
}

const speak = ({ sound }) => sound
speak(cat) //=> "meow"
Thread Thread
 
josetorreschang profile image
jose-torres-chang

Although I can see what you are pointing, what is difficult, is to find the best way to avoid using this in a real application. Thanks a lot, this has been one of the most significant discussion this year.

Thread Thread
 
joelnet profile image
JavaScript Joel • Edited

That is because you have been taught to use this. With OOP, you are pretty much stuck with this (unless of course you use nothis). When you learn functional reactive programming, you'll find this to no longer be necessary and magically this just vanishes from your codebase.

Check out one of my projects here github.com/joelnet/bitcoin-all-tim.... This is a real world application. It follows what I preach from How I rediscovered my love for JavaScript after throwing 90% of it in the trash.

You won't find any references to this, var, let, if, switch, for, the function keyword or other staples of classic javascript programs.

Thread Thread
 
ilmtitan profile image
Jim Przybylinski • Edited

If you use typescript and modify the cat speak code to use an explicit if, you get a compile error.

const cat = {
    sound: 'meow',
    speak(this: {sound: string}) { return this.sound }
}

const speak = cat.speak
speak() // <= Compile error: void is not assignable to { sound: string }.
Thread Thread
 
joelnet profile image
JavaScript Joel

It's pretty nice that this will happen at compile time and not runtime.