Creating your own JavaScript

Karolis Masiulis
2 min readAug 24, 2016

--

tl;dr If you are using JSX, Babel is tied to your codebase. You can use Babel to fix some of the ugly parts in JavaScript. But should you?

Back when React 0.13-beta was released I refactored a large project from using React.createClass to ES6 classes. There was only one difference between the two. React.createClass binds “this” to methods by default but classes does not.

There are multiple solutions to this problem (pun not intended):

  • Revert back to React.createClass - no practical cons, but you are relying on a magic that createClass does and don’t use the standard class.
  • Use .bind on methods in the constructor or in the render - a lot of manual boilerplate. Binding in the constructor does not work with React Hot Loader and binding in the render creates a new function on every render.
  • Use arrow functions with class properties. This is not-yet-standard JavaScript feature, but can be used with babel stage-0. Compiles down to a method binding in the constructor, so still not hot-reloadable.
  • Make JavaScript classes automatically bind methods by changing the language itself. Pros and cons are discussed bellow.

Rethinking best practices… again

Out of above mentioned solutions, class properties and decorators are available only when you are using Babel and there is a chance that they will never become a part of JavaScript. JSX will most likely never become a part of JavaScript. Our React code base is already tied to Babel. Then why not use the power of Babel to fix JavaScript oddities and make it more predictable?

It is quite easy to write a Babel plugin that autobinds class methods, you can check my implementation here: https://github.com/UgnisSoftware/babel-plugin-autobind-class-methods.

It solves problems that other solutions had like manual boilerplate and support for hot reloading. Apart from one new problem - that’s no longer JavaScript. But it does not break the JavaScript either. (unless you relied on the fact that unbound “this” references the global object, in which case may God have mercy on your soul). That means adding the plugin to an existing program breaks nothing but makes further development smoother.

The question is, how much of a language do you have to change to still consider it the same language? Is JSX still JavaScript? It looks like Babel opened up the Pandora’s box when everyone can create their own version of JavaScript.

Babel plugins are threading on thin ice between making development less painful and increasing JavaScript fatigue. They allow extending the language in a way that reduces boilerplate and prevents bugs. On the other hand, changing the language too much would make impossible to share code and best practices with others.

--

--

Karolis Masiulis

Building software that builds software. Automation, AI, compile-to-JavaScript tools