DEV Community

James L
James L

Posted on

๐ŸŽ„JS Advent #4 - call() and apply() ๐ŸŽ„

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 a this 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());
Enter fullscreen mode Exit fullscreen mode
  • 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)); 
Enter fullscreen mode Exit fullscreen mode

The apply() function

  • The apply method operates almost exactly the same as the call 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
Enter fullscreen mode Exit fullscreen mode

< JS Advent 3 - Object.hasOwnProperty()

Top comments (0)