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:
// ONLINE-RUNNER:browser;
'use strict'; // remove it and run to see what happened with this keyword
function print(a, b){
console.log(this + ' ' + (a + b));
}
print(1, 2); // undefined 3
print.call(1, 2, 3); // 1 5
print.apply(1, [2, 3]); // 1 5
var proxy = print.bind(1);
proxy(2, 3); // 1 5
proxy(4, 5); // 1 9
1. Direct calling method example
This is the way we usually call the function.
// ONLINE-RUNNER:browser;
var Printer = {
name: 'PRINTER',
print: function(a, b, c) {
var text = 'context-name: ' + this.name + ', '
+'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';
console.log(text);
}
}
Printer.print(1, 2, 3);
2. Function
call
method example
In this approach it is possible to call the function with a new context - arguments are placed after context.
// ONLINE-RUNNER:browser;
var Printer = {
name: 'PRINTER',
print: function(a, b, c) {
var text = 'context-name: ' + this.name + ', '
+'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';
console.log(text);
}
}
var Manager = {
name: 'MANAGER'
};
Printer.print.call(Manager, 1, 2, 3);
3. Function
apply
method example
In this approach it is possible to call the function with a new context - arguments are passed as an array.
// ONLINE-RUNNER:browser;
var Printer = {
name: 'PRINTER',
print: function(a, b, c) {
var text = 'context-name: ' + this.name + ', '
+'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';
console.log(text);
}
}
var Manager = {
name: 'MANAGER'
};
Printer.print.apply(Manager, [1, 2, 3]);
4. Function
bind
method example
With this approach, the proxy function is created with new context.
// ONLINE-RUNNER:browser;
var Printer = {
name: 'PRINTER',
print: function(a, b, c) {
var text = 'context-name: ' + this.name + ', '
+'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';
console.log(text);
}
}
var Manager = {
name: 'MANAGER'
};
var printProxy = Printer.print.bind(Manager);
printProxy(1, 2, 3);
Another way how to create a proxy method is:
// ONLINE-RUNNER:browser;
function createProxy(context, action) {
var proxy = function() {
return action.apply(context, arguments);
};
return proxy;
}
// Usage example:
var Printer = {
name: 'PRINTER',
print: function(a, b, c) {
var text = 'context-name: ' + this.name + ', '
+'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';
console.log(text);
}
}
var Manager = {
name: 'MANAGER'
};
var printProxy = createProxy(Manager, Printer.print);
printProxy(1, 2, 3);