DEV Community

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

Collapse
 
joelnet profile image
JavaScript Joel

Sometimes you do not have control over the code you are using. An example of this would be 3rd party libraries.

I am forced to use this here because that is how the library is written.

events.on('button.*', function() {
  console.log('event:', this.event)
})

this prevents me from writing code like this

events.on('button.*', () => console.log('event:', this.event))
//=> Error

or like this:

events.on('button.*', ({ event }) => console.log('event:', event))
//=> Error

But with nothis I can write my function like this:

events.on('button.*', nothis(({ event }) => console.log('event:', event)))
Collapse
 
patroza profile image
Patrick Roza

Alright, so nothis is great for serving as an adapter to third party code, but I think for own code using the es6 constructs like class, arrow function and e.g linter should suffice.
I would also prefer to use the nothis on the events object to fix all its methods at once.
Or imo better have another wrapping approach that hides the poor use of this in events.on, and the use of nothis, so that we dont have to repeat it, nor remember it each time we want to use events.on

Thread Thread
 
joelnet profile image
JavaScript Joel

Totally agree. Great suggestion. I just added a helper function to apply all functions at once.

What are your thoughts on this?

import React from 'react'
import nothisAll from 'nothis/nothisAll'

class Counter extends React.Component {
  state = { count: 0 }

  constructor() {
    super()
    nothisAll(this)
  }

  increment({ setState }) {
    setState(({ count }) => ({ count: count + 1 }))
  }

  render({ increment, state }) {
    return (
      <div>
        <button onClick={increment}>{state.count}</button>
      </div>
    )
  }
}