NO. THIS.
The complete elimination and eradication of JavaScript's this.
If this is so difficult to reason about, why don't we just stop using it? Seriously. Why. don't. we. just. stop. using. it.?
When a function is decorated with the nothis
function decorator it will pass this
as the first argument. Read more on function decorators here.
Now you can remove all those annoying var self = this
lines as they are now completely unnecessary!
Installation
npm install nothis
Functions
decorator
- @context function decorator for Class functions.nothis
- passesthis
as an argument.fixthis
- Prevents the rebinding ofthis
.nothisAll
- Prevents the rebinding ofthis
for React.
nothis :: function -> function
Example: Decorator
Basic JavaScript object
sound = 'meow' @context { return ctxsound } @context ctxsound const cat = cat //=> 'meow'cat //=> 'meow'
Example 1: Basics
Basic JavaScript object
// 😞 GROSS: thisconst cat = sound: 'meow' { return thissound } // 🔥 LIT: nothis const cat = sound: 'meow' speak:
Example 2: Arrow functions
Arrow functions with this
won't work. But with nothis
you can still access the context.
// 😞 GROSS: thisconst cat = sound: 'meow' thissoundcat//=> undefined // 🔥 LIT: nothisconst cat = sound: 'meow' speak: cat//=> "meow"
Example 3: Multiple arguments
const cat = sound: 'meow' speak: cat// => "meow!"
Example 4: Clarity
Easily know what your context is.
// 😞 GROSS: thisconst cat = sound: 'meow' { return thissound } { }cat//=> Error: this.speak is not a function // 🔥 LIT: nothisconst cat = sound: 'meow' { return thissound } crazy: cat// => "meow"// => "meow"// => "meow"
Example 5: 3rd Party Libraries
3rd party libraries sometimes require you to use this
. F that.
// 😞 GROSS: this // 🔥 LIT: nothis
You can also use parameter destructuring in ES6 arrow functions.
const events = wildcard: true // 😞 GROSS: thisevents // 🔥 LIT: nothis + destructuring!events events
fixthis :: object -> object
Sometimes this
will get rebound to another context when you least expect it. Consider this example.
// 😞 GROSS: thisconst cat = sound: 'meow' { return thissound }const speak = catspeak // => undefined
You can prevent this from happening by using fixthis
.
// 🔥 LIT: fixthis const cat = const speak = catspeak // => "meow"
ES6 Classes
Classes won't save you from the problems of this
.
// 😞 GROSS: this { thissound = 'meow' } { return thissound } const cat = const speak = catspeak// => Cannot read property 'sound' of undefined
You still can fixthis
it.
// 🔥 LIT: fixthis { thissound = 'meow' } { return thissound } const cat = const speak = catspeak//=> "meow"
fixthisReact :: object -> void
Apply fixthisReact
to your React component and never have to use this
again!
// 🔥 LIT: no this in sight!Component state = count: 0 { super } { } { return <div> <button onClick=increment>statecount</button> </div> }