For the month of December I have challenged myself to write 24 articles about JS up until Xmas.
The fourth installment in this series is about call()
and apply()
.
The call() function
- The
call
method calls a function. It takes athis
value as its first parameter and then optional arguments as a list for each parameters of that function.
Example:
//globalThis
x = 2; y = 3;
const obj = {
x: 10;
y: 20;
}
function add () {
return this.x + this.y;
}
console.log(add.call(obj)); // 30
// 5 - globalThis is used (However in strict mode globalThis is not substituted so it would return NaN)
console.log(add.call());
- Passing parameters as a list:
// globalThis
x = 2; y = 3;
const obj = {
x: 10;
y: 20;
}
function add (a, b) {
return this.x + this.y + a + b;
}
console.log(add.call(obj, 20, 30)); // 80
// 55 - as null or undefined is converted to the globalThis object in non strict mode
console.log(add.call(null, 20, 30));
The apply() function
- The
apply
method operates almost exactly the same as thecall
method except that it takes an array of parameters instead of as a list.
Example:
// globalThis
x = 2; x = 3;
const obj = {
a: 10;
b: 20;
}
function add (a, b) {
return x + y + this.a + this.b;
}
console.log(add.apply(obj, [20, 30])); // 80
console.log(add.apply(null, [20, 30])); // 55
Top comments (0)