Languages
[Edit]
EN

JavaScript - what is the difference between call, apply and bind (call vs apply vs bind)?

1 points
Created by:
JustMike
26670

In JavaScript it is possible to change context of executed method. It mans we can change this keyword reference during executing some function (method). In this article brief comparision of each method has been presented.

1. Methods diffence

Method name description
myFunction.call(context, ...) calls method with new context; after context arguments passed to myFunction should be placed
myFunction.apply(context, argsArray) calls method with new context; after context array of arguments of myFunction should be placed
myFunction.bind(context) creates proxy function with new context and returns reference to it

2. Methods comparision example

function print(a, b, c) {
    var text = 'context-name: ' + this.name + ', '
        +'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';

    console.log(text);
}

var Manager = {
    name: 'MANAGER'
};


print(1, 2, 3);

print.call(Manager, 1, 2, 3);
print.apply(Manager, [1, 2, 3]);

var printProxy = print.bind(Manager);
    
printProxy(1, 2, 3);

Output:

context-name: undefined, argument-values: [a=1, b=2, c=3]
context-name: MANAGER, argument-values: [a=1, b=2, c=3]
context-name: MANAGER, argument-values: [a=1, b=2, c=3]
context-name: MANAGER, argument-values: [a=1, b=2, c=3]

Note: methods comparison with object methods as source code examples has been presented here.

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join