Guys can any one explain context to use call
and apply
methods in Javascript?
Why to use call
and apply
instead of calling a function directly ?
Difference between call() and apply() method: The only difference is call() method takes the arguments separated by comma while apply() method takes the array of arguments. Example 1: This example uses call() method to call a function.
Call invokes the function and allows you to pass in arguments one by one. Apply invokes the function and allows you to pass in arguments as an array. Bind returns a new function, allowing you to pass in a this array and any number of arguments.
Summary. The apply() method invokes a function with a given this value and arguments provided as an array. The apply() method is similar to the call() method excepts that it accepts the arguments of the function as an array instead of individual arguments.
Summary. call : binds the this value, invokes the function, and allows you to pass a list of arguments. apply : binds the this value, invokes the function, and allows you to pass arguments as an array. bind : binds the this value, returns a new function, and allows you to pass in a list of arguments.
You use call
or apply
when you want to pass a different this
value to the function. In essence, this means that you want to execute a function as if it were a method of a particular object. The only difference between the two is that call
expects parameters separated by commas, while apply
expects parameters in an array.
An example from Mozilla's apply
page, where constructors are chained:
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.apply(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);
What Product.apply(this, arguments)
does is the following: The Product
constructor is applied as a function within each of the Food
and Toy
constructors, and each of these object instances are being passed as this
. Thus, each of Food
and Toy
now have this.name
and this.category
properties.
Only if you use call
or apply
you can modify the this
context inside the function.
Unlike other languages - in JavaScript this
does not refer to the current object - rather to the execution context and can be set by the caller.
If you call a function using the new
keyword this
will correctly refer to the new object (inside the constructor function)..
But in all other cases - this
will refer to the global object unless set explicitly through call
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With