Javascript - Function Function apply()

Introduction

The apply() method accepts two arguments: the value of this inside the function and an array of arguments.

This second argument may be an instance of Array, but it can be the arguments object.

Consider the following:

function sum(num1, num2){
    return num1 + num2;
}

function callSum1(num1, num2){
    return sum.apply(this, arguments);    //passing in arguments object
}

function callSum2(num1, num2){
    return sum.apply(this, [num1, num2]); //passing in array
}

console.log(callSum1(10,10));   //20
console.log(callSum2(10,10));   //20

In this example, callSum1() executes the sum() method, passing in this as the this value and passing in the arguments object.

The callSum2() method also calls sum(), but it passes in an array of the arguments instead.

In strict mode, the this value of a function called without a context object is not coerced to window.

this becomes undefined unless explicitly set by either attaching the function to an object or using apply() or call().