JavaScript Decorators: True Power In ES7

by | Jul 6, 2016

JavaScript can be pretty annoying at times. You would think that with classes implemented in ES6, this would be solved. For me, the most annoying part of programming is typing. So every time I need to call a class member in React, I have to bind the function to “this.” However, with ES7 decorators, its possible to use a library function (autobind-decorator) to do automatic binding of “this” to all class members or individual member functions. But if you’re using Babel 6, which is the most current version, you have to use (babel-plugin-transform-decorators-legacy), since ES7 decorators have not actually been finalized.

// example without autobind:

class Toad extends Component {
    contructor(props) {
        super(props);
        this.state = {
            distance: 1,
        }
        // have to bind this context to jump function
        this.jump = this.jump.bind(this);
    }
    jump() {
        alert("jumped " + this.state.distance);
    }
    jump2() {
        alert("jumped " + this.state.distance * 2);
    }
    render() {
        return (
            <div>
                <div onClick={this.jump}></div>
                {/* bind jump2 function */}
                <div onClick={this.jump2.bind(this)}></div>
            </div>
        )
    }
}
// example without autobind:
import autobind from 'autobind-decorator'
@autobind
class Autotoad extends Component {
    contructor(props) {
        super(props);
        this.state = {
            distance: 1,
        }
    }
    jump() {
        alert("jumped " + this.state.distance);
    }
    render() {
        return (
            <div onClick={this.jump}>
            </div>
        )
    }
}

At least when using arrow function syntax, the context of “this” is preserved, so code is no longer filled with references to “this,” “in,” “that,” or “self.”

So what are decorators? Basically, functions that wrap around other functions. Decorators can be more powerful than the actual language. They can bypass the language runtime and translate into statically compiled code. For example, Numba compiles functions to machine-code based on which functions have the decorator.

Should languages be changeable by the user based on preferences? What’s interesting about transpiling is that personal preferences can be satisfied instead of strict compatibility with standards. What I don’t understand is why it is not more common around older languages like C++.

Recent Posts