Cedric Reichenbach Cedric Reichenbach - 1 year ago 56
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,
simply executes the corresponding function with the function's
set to the first argument and passing further arguments to it.
is already a property of the object we want to be
, it seems that
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
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 Source

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'"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download