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
Written by Steven Iseki
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#