0

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;
    }
}
Alex Yong
  • 7,425
  • 8
  • 24
  • 41

3 Answers3

1

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

0

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

Community
  • 1
  • 1
Sateesh
  • 1,327
  • 9
  • 12
  • what is that needed? it worked without it in above case. I know what's the use of bind, I'm just asking why specifically why it's needed in my case. – Alex Yong Feb 23 '17 at 04:00
  • In your case bind() method used to reuse methods and curry a function because bind() allows- set the value of "this" to an specific object. This becomes very helpful as sometimes "this" is not what is intended. – Sateesh Feb 23 '17 at 06:26
0

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 thisand
  • 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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143