1

I was wondering is it a good practice to bind constant arguments to method in constructor or is there some better alternatives?

f.e.

constructor() {
    super();

    this.openModalWithFirstTabActive = this.openModal.bind(this, TAB.FIRST);
    this.openModalWithSecondTabActive = this.openModal.bind(this, TAB.SECOND);
}

openModal(tabId) {
   const {
       openModal,
   } = this.props;

   /*
       lots of logic and stuff
   */

   openModal({
       activeTabId: tabId,
       ...restProps,
   });
}

EDIT

I'll provided more code and will describe my usage case for better understanding.

I've updated with openModal method, in my usecase it's much larger and has more logic in it.

So, i have a modal, in which there's two tabs. I have two buttons, open pressing button 1 modal needs to open and first tab needs to be active, upon pressing button 2 modal needs to open and second tab needs to be active.

I bind two methods in constructor which both call this.openModal only with different activeTabId specified. This avoids code duplication and arrow functions.

So my question would be is there any better alternative to this?

Simas.B
  • 724
  • 1
  • 13
  • 31

1 Answers1

2

There is no point in binding a constant value to the function since they can directly be accessed inside the method. Also, since the binded arguments are the first to a function it might lead to confusion when debugging or handling the logic in the methods

When you use bind in constructor, it would lead to two instances of the function being created which is alright and won't affect the performance.

In case you have scenarios where you need to pass dynamic value to the methods without using bind in render, you can refer the following post

How to avoid bind or inline arrow functions inside render method

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400