svjr4q
Last Updated: February 25, 2016
·
430
· steveniseki
Stevenm

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    
Say Thanks
Respond