简体   繁体   中英

bind this is optional in class if no constructor?

I have below class, but I'm confused by the bind this here. The class don't have a constructor and super(), why did he need to do bind this on setAll method? I removed the bind this, the application still work and no error.

class PushScheduleActions {

    /**
     * Request all API
     */
    fetchAll(params) {
        return dispatch => {
            dispatch(params);

            PushScheduleApi.getAll(params)
                .then(this.setAll.bind(this));//why use bind this here?
                .catch(this.setError.bind(this));
        }
    }

    setAll(data) {
        return data;
    }
}

There is no relation between constructor, super and bind.

What bind does? it returns a new function with the context user passed.

In your case, PushScheduleApi success case you are passing a new setAll function which is returned by bind method.

  1. since your setAll function doesn't use context, you don't need to pass the context.

  2. dispatch is an arrow function, so context is inherited. So you dont need bind method. you can simply use this.setAll

The bind() function creates a new bound function (BF). A BF is an exotic function object (a term from ECMAScript 2015 ) that wraps the original function object. Calling a BF generally, results in the execution of its wrapped function.

For more detail follow this link i hope it will help you a lot to understand to bind() method Use of the JavaScript 'bind' method

The class don't have a constructor and super()

That's completely irrelevant.

why did he need to do bind this on setAll method?

The method only needs to be bound if

  • it uses this and
  • this should refer to what this refers to inside fetchAll (likely an instance of PushScheduleActions ).

Since setAll doesn't reference this , there is no reason to bind.

However , the whole setAll method is unnecessary. The code would work exactly the same without .then(this.setAll.bind(this)) . That makes me think that PushScheduleActions is supposed to be subclassed and child classes are supposed to overwrite setAll . Now, the child class' setAll might use this and expect it to refer to the instance. Since the parent class ( PushScheduleActions ) can't know that, binding the method is safer since it will ensure that child class implementations of setAll will work regardless if they use this or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM