JavaScript call() vs apply()

call() and apply() method are Function class’s core functions.

exaple 1 :-

function Product(name, price) {
    this.name = name;
    this.price = price;

    if (price < 0)
        throw RangeError(‘Cannot create product “‘ + name + ‘” with a negative price’);
    return this;
}

function Food(name, price) {
    Product.call(this, arguments);
    this.category = ‘food’;
}
Food.prototype = new Product();

function Toy(name, price) {
    Product.apply(this, arguments);
    this.category = ‘toy’;
}
Toy.prototype = new Product();

var cheese = new Food(‘feta’, 5);
var fun = new Toy(‘robot’, 40);

console.log(JSON.stringify(cheese));
console.log(JSON.stringify(fun));

exaple 2 :-

function theFunction(name, profession) {
    alert(“My name is ” + name + ” and I am a ” + profession + “.”);
}

theFunction(“John”, “fireman”);
theFunction.apply(undefined, [“Susan”, “school teacher”]);
theFunction.call(undefined, “Claude”, “mathematician”);

call() :-
1. Any no of arguments to the function.
2. it will get parameters as like arguments to be passed to the function.

eg. functionName.call( this, a, b);
    . this will be the scope of the function.
    . u ll get function(a,b);

eg. functionName.call( this, array/string);
    . this will be the scope of the function.
    . u ll get function([a],b);

apply() :-
1. only two arguments to the function.
2. It ill get no of args based on the array lenth.

ie. functionName.call( this, arguments);
ie. functionName.call( this, array);

eg. functionName.call( this, [‘a’,’b’);
    . this will be the scope of the function.
    . u ll get function(a,b);