Cedric Reichenbach Cedric Reichenbach - 25 days ago 7
Javascript Question

Difference between obj.func(arg) and obj.func.bind(obj, arg)

I just came across a the following structure in a piece of React code (names changed):

<MyActionComponent callback={this.func.bind(this, arg)}>


From what I understand,
bind
simply executes the corresponding function with the function's
this
set to the first argument and passing further arguments to it.
Since
func
is already a property of the object we want to be
this
, it seems that
this.func(arg)
would result in the same behaviour.

I fail to see the motivation behind what seems like a more complex syntax for identical functionality.
Is there any context where
obj.func(arg)
would behave differently compared to
obj.func.bind(obj, arg)
? Or are there non-technical aspects (e.g. convention, consistency) I'm unaware of?

Answer

The critical difference is that obj.func(arg) executes the function whereas func.bind(obj, arg) does not execute the function. It only ensures that this will be bound to obj once the function get's actually executed.

See here:

var obj = {
  fooFn: function() {console.log("this = ", this)}
}

obj.fooFn() // => prints "this = [Object]"

var boundFn = obj.fooFn.bind("bar")
boundFn() // => prints "this = 'bar'"