Function call()
Why function.call ?
JavaScript call () allows a function of an object to be assigned and called to a different object. Call the call () object once. You can then inherit from another object without the need for a new object.
CALL : A function with argument provide individually. If you know the arguments to be passed or there are no argument to pass you can use call.
APPLY : Call a function with argument provided as an array. You can use apply if you don’t know how many argument are going to pass to the function.
Let’s understand the logic with a small example:
let person = {
introduce: function(surname){
console.log("my name is " + this.name +
" and my surname is " + surname);
}
}
person.introduce.call({ name: "oliver" }, "allen")
my name is oliver and my surname is allen
JavaScript Function Call() Examples
Example 1
let arr_1 = { object: "object 1" };
let arr_2 = { object: "object 2" };
function control(x, y) {
console.log(this.object, x, y);
}
control.call(arr_1, " =>", "this is function.call");
control.apply(arr_2, [" =>", "this is function.apply"]);
output:
object 1 => this is function.call
object 2 => this is function.apply
Example 2
function car() {
console.log(this,arguments)
}
function carAdd() {
car.call(this, arguments);
}
let car1 = {name: "bmw"}
carAdd.call(car1)
output:
{name: “bmw”}
Example 3
Reminding: The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method.”
let numbers = {
num1: 20,
num2: 30,
num3: 40
}
let arr = function (num4) {
return this.num1 + this.num2 + this.num3 + num4;
}
console.log(arr.call(numbers, 50));
console.log(arr.apply(numbers, [50]));
output:
140
140
Example 4
let arr = {
bookInfo: function () {
return this.bookName + " / " + this.bookDate;
}
}
let book = {
bookName: "harry potter",
bookDate: 2000
}
console.log(arr.bookInfo.call(book))
output:
harry potter / 2000
Example 5
function bookinfo(name, date) {
this.name = name;
this.date = date;
}
function add(name, date) {
bookinfo.call(this, name, date);
this.info = "book";
}
console.log(new add("harry potter", 2000).name);
console.log(new add("harry potter", 2000).date);
output:
harry potter
2000
Example 6
function salary(){
this.good = good;
this.middle = middle;
this.bad = bad
}
let controlSalary = function(){
console.log(this, arguments);
}
let goodSalary = { good: 5000 };
let middleSalary = { middle: 3000 };
let badSalary = { bad: 1000 };
controlSalary.call(controlSalary.call(goodSalary));
controlSalary.call(controlSalary.call(middleSalary));
controlSalary.call(controlSalary.call(badSalary));
output:
{good: 5000}
{middle: 3000}
{bad: 1000}
Browser Support
Chrome | yes |
Edge | yes |
Firefox | 1 |
Internet Explorer | yes |
Opera | yes |
Safari | yes |
Android webview | yes |
Chrome for Android | yes |
Edge mobile | yes |
Firefox for Android | 4 |
Opera Android | yes |
2 Comments »