Call() vs Bind() vs Apply()
These three methods are used to change the value of this
for a function. They’re pretty similar but have some crucial differences.
This is a favourite JavaScript interview question so here’s a quick explanation.
Call(this, parameters)
The call
method immediately calls a function with a given this
value. Parameters for the function are passed down individually by separating them with commas.
someFunction.call(thisValue, 'list', 'of', 'parameters');
Apply(this, parameters)
apply
is almost identical to call
: it immediately calls the function, but it accepts function parameters as an array instead of individually.
someFunction.apply(thisValue, ['list', 'of', 'parameters']);
call
and apply
are basically interchangeable, it comes down to your personal preference as to which you’ll use.
Bind(this, parameters)
bind
is a little different to the other two. Instead of calling the function, it returns a new one with a given this
value attached.
Just like call
, this takes any number of parameters.
const bindThis = someFunction.apply(thisValue);
bindThis();
The bind
method should be familiar if you work with React. JavaScript doesn't automatically bind class methods, so you’ll generally bind your methods in the class constructor.
constructor(props) {
super(props)
// Without this line, `this` will be undefined in someMethod
this.someMethod = this.someMethod.bind(this);
}