EN
JavaScript - different ways to call function
12 points
In this article, we would like to show you how to call functions in different ways in JavaScript.
Quick solutions:
xxxxxxxxxx
1
'use strict'; // remove it and run to see what happened with this keyword
2
3
function print(a, b){
4
console.log(this + ' ' + (a + b));
5
}
6
7
print(1, 2); // undefined 3
8
9
print.call(1, 2, 3); // 1 5
10
print.apply(1, [2, 3]); // 1 5
11
12
var proxy = print.bind(1);
13
14
proxy(2, 3); // 1 5
15
proxy(4, 5); // 1 9
This is the way we usually call the function.
xxxxxxxxxx
1
var Printer = {
2
name: 'PRINTER',
3
print: function(a, b, c) {
4
var text = 'context-name: ' + this.name + ', '
5
+'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';
6
7
console.log(text);
8
}
9
}
10
11
Printer.print(1, 2, 3);
In this approach it is possible to call the function with a new context - arguments are placed after context.
xxxxxxxxxx
1
var Printer = {
2
name: 'PRINTER',
3
print: function(a, b, c) {
4
var text = 'context-name: ' + this.name + ', '
5
+'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';
6
7
console.log(text);
8
}
9
}
10
11
var Manager = {
12
name: 'MANAGER'
13
};
14
15
Printer.print.call(Manager, 1, 2, 3);
In this approach it is possible to call the function with a new context - arguments are passed as an array.
xxxxxxxxxx
1
var Printer = {
2
name: 'PRINTER',
3
print: function(a, b, c) {
4
var text = 'context-name: ' + this.name + ', '
5
+'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';
6
7
console.log(text);
8
}
9
}
10
11
var Manager = {
12
name: 'MANAGER'
13
};
14
15
Printer.print.apply(Manager, [1, 2, 3]);
With this approach, the proxy function is created with new context.
xxxxxxxxxx
1
var Printer = {
2
name: 'PRINTER',
3
print: function(a, b, c) {
4
var text = 'context-name: ' + this.name + ', '
5
+'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';
6
7
console.log(text);
8
}
9
}
10
11
var Manager = {
12
name: 'MANAGER'
13
};
14
15
16
var printProxy = Printer.print.bind(Manager);
17
18
printProxy(1, 2, 3);
Another way how to create a proxy method is:
xxxxxxxxxx
1
function createProxy(context, action) {
2
var proxy = function() {
3
return action.apply(context, arguments);
4
};
5
return proxy;
6
}
7
8
// Usage example:
9
10
var Printer = {
11
name: 'PRINTER',
12
print: function(a, b, c) {
13
var text = 'context-name: ' + this.name + ', '
14
+'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';
15
16
console.log(text);
17
}
18
}
19
20
var Manager = {
21
name: 'MANAGER'
22
};
23
24
var printProxy = createProxy(Manager, Printer.print);
25
26
printProxy(1, 2, 3);