Last Updated: September 29, 2021
·
2.033K
· 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    

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside