HiveBrain v1.2.0
Get Started
← Back to all entries
principlejavascriptCritical

Javascript call() & apply() vs bind()?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
callbindjavascriptapply

Problem

I already know that apply and call are similar functions which set this (context of a function).

The difference is with the way we send the arguments (manual vs array)

Question:

But when should I use the bind() method ?

var obj = {
  x: 81,
  getX: function() {
    return this.x;
  }
};

alert(obj.getX.bind(obj)());
alert(obj.getX.call(obj));
alert(obj.getX.apply(obj));


jsbin

Solution

I created this comparison between function objects, function calls, call/apply and bind a while ago:

.bind allows you to set the this value now while allowing you to execute the function in the future, because it returns a new function object.

Context

Stack Overflow Q#15455009, score: 274

Revisions (0)

No revisions yet.