EN
JavaScript - difference between call, apply and bind
1 points
In JavaScript, it is possible to change the context of the executed method. It means we can change this
keyword reference during executing some function (method). In this article brief comparison of each method has been presented.
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 a proxy function with a new context and returns a reference to it |
xxxxxxxxxx
1
function print(a, b, c) {
2
var text = 'context-name: ' + this.name + ', '
3
+'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';
4
5
console.log(text);
6
}
7
8
var Manager = {
9
name: 'MANAGER'
10
};
11
12
13
print(1, 2, 3);
14
15
print.call(Manager, 1, 2, 3);
16
print.apply(Manager, [1, 2, 3]);
17
18
var printProxy = print.bind(Manager);
19
20
printProxy(1, 2, 3);
Output:
xxxxxxxxxx
1
context-name: undefined, argument-values: [a=1, b=2, c=3]
2
context-name: MANAGER, argument-values: [a=1, b=2, c=3]
3
context-name: MANAGER, argument-values: [a=1, b=2, c=3]
4
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.