Last Updated: September 29, 2021
·
1.441K
· steveniseki

call and apply in JavaScript

The call method calls a function with a given <i>this</i> value and arguments provided individually.

The apply method calls a function with a given <I>this</I> value and arguments provided as an array.

var obj = {
    name: "obj"

    doSomething : function(x,y){
        var total =  x + y;
        alert(this.name + " = " + total);
    }
}

var foo = { name : "foo" };

var bar = { name : "bar" };

obj.doSomething.call(bar,3,6); // alerts bar = 9
obj.doSomething.apply(foo,[9,3]); // alerts foo = 12