Categories
interview

Javascript call() vs apply() vs bind()

call

The call() is a predefined Javascript function which can used to call a method of an object while passing it another object. For example, if you look at the following code, you will observe that the object being passed into the call() method replaces the this variable of the object whose method is being invoked.

Output

Demo

apply

The apply() is a predefined Javascript function similar to the call() function, the difference being that we can also pass arguments as arrays. For example.

Output

Demo

Note
In non-strict mode, when null is the first argument for apply(), then the default global value will be used for this. Otherwise the first argument passed in apply() is used for the value of this.

bind

The bind() function is a predefined Javascript function too. It is used to create a new function, that can be bound by what ever object you pass it with. For example.

Output

Demo