I was getting annoyed writing so much boiler plate binding code in the constructor of my react classes, e.g.
this.foo = this.foo.bind(this);
this.bar = this.bar.bind(this);
To avoid errors at runtime due to the way JS 'this' statement works. I created a simple autoBind(instance) function:
function autoBind(instance) {
const props = Object.getOwnPropertyNames(Object.getPrototypeOf(instance)).filter(p => typeof instance[p] === 'function');
props.forEach(p => instance[p] = instance[p].bind(instance));
}
This is invoked in a constructor as follows...
constructor(props) {
super(props)
autoBind(this)
}
It seems to work fine... but I'm curious, what might go wrong here? What are the risks of this approach?