I have been using React for a while now, and I have become comfortable with the concept that I must manually bind my component methods to my component instance, as React made th
You can make you ES6 class methods auto-bind with a little boiler-plate in the constructor:
function autobind() {
for (let prop of Object.getOwnPropertyNames(Object.getPrototypeOf(this))) {
if (prop === 'constructor' || typeof this[prop] !== 'function') continue;
this[prop] = this[prop].bind(this);
}
}
class Test {
constructor() {
autobind.call(this);
this.message = 'hello all!';
}
method1(){ return this.method2(); }
method2(){ console.log(this.message);}
}
let test = new Test();
let b = test.method1;
b();
UPDATE:
I have since found a Babel Plugin that translates the upcomping ES Class Fields & Static Properties which you can use for functions that need to be bound to the this
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.__proto__.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"