1

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?

ConfusedNoob
  • 9,826
  • 14
  • 64
  • 85
  • 1
    i think using functional component is easier than ES6 class – Shreyas Jadhav Apr 07 '21 at 04:16
  • One point is it looks like it re-binds the inherited React class functions, though I don't think binding twice should cause any major issues. That being said you could always just use class fields arrow functions for component's methods - just define them with arrow functions, then you don't need to bind at all: https://stackoverflow.com/questions/32192682/react-js-es6-avoid-binding-this-to-every-method - But as Shreyas said, if you're writing new code you should use functional components, that's the way React is shifting – Jayce444 Apr 07 '21 at 04:18
  • 1
    Why not just use arrow functions? The binding of `this` is done "automagically" for you. Seems more work/effort for little to no gain creating and using that utility. – Drew Reese Apr 07 '21 at 04:42

0 Answers0