Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xyzdata/d2e28b6720c54553bb506754a934cb47 to your computer and use it in GitHub Desktop.
Save xyzdata/d2e28b6720c54553bb506754a934cb47 to your computer and use it in GitHub Desktop.
ES7 & Property initializer syntax & React auto bind this

ES7 & Property initializer syntax

React auto bind this

property-initializer-syntax-auto-bind-this

babel-plugin

babel-plugin-transform-class-properties

$ npm i -D babel-plugin-transform-class-properties

https://babeljs.io/docs/plugins/transform-class-properties/

    
//
class Bork {
    //Property initializer syntax
    instanceProperty = "bork";
    boundFunction = () => {
        return this.instanceProperty;
    };
    //Static class properties
    static staticProperty = "babelIsCool";
    static staticFunction = function () {
        return Bork.staticProperty;
    };
}

let myBork = new Bork;

// Property initializers are not on the prototype.
console.log(myBork.prototype.boundFunction); 
// > undefined

// Bound functions are bound to the class instance.
console.log(myBork.boundFunction.call(undefined)); 
// > "bork"

// Static function exists on the class.
console.log(Bork.staticFunction()); 
// > "babelIsCool"

.babelrc

// without options
{
    "plugins": ["transform-class-properties"]
}

// with options
{
    "plugins": [
        ["transform-class-properties", { "spec": true }]
    ]
}
@xyzdata
Copy link
Author

xyzdata commented Jul 3, 2017

@xyzdata
Copy link
Author

xyzdata commented Jul 3, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment