Why we need call and apply in javascript?

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 ?

Eugene S

6,5227 gold badges58 silver badges89 bronze badges

asked Dec 28, 2011 at 17:49

1

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.

answered Dec 28, 2011 at 17:52

kevinjikevinji

10.3k4 gold badges37 silver badges57 bronze badges

6

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

kevinji

10.3k4 gold badges37 silver badges57 bronze badges

answered Dec 28, 2011 at 17:51

Why we need call and apply in javascript?

TigraineTigraine

22.9k10 gold badges65 silver badges108 bronze badges

2

You use .call() when you want to cause a function to execute with a different this value. It sets the this value as specified, sets the arguments as specified and then calls the function. The difference between .call() and just executing the function is the value of the this pointer when the function executes. When you execute the function normally, javascript decides what the this pointer will be (usually the global context window unless the function is called as a method on an object). When you use .call(), you specify exactly what you want this to be set to.

You use .apply() when the arguments you want to pass to a function are in an array. .apply() can also cause a function to execute with a specific this value. .apply() is most often used when you have an indeterminate number of arguments that are coming from some other source. It is often used too pass the arguments from one function call to another by using the special local variable arguments which contains an array of arguments that were passed to your current function.

I find the MDN references pages for .call() and .apply() helpful.

answered Dec 28, 2011 at 18:11

Why we need call and apply in javascript?

jfriend00jfriend00

653k90 gold badges927 silver badges930 bronze badges

1

If you have experience with jQuery, you will know that most functions take use of the this object. For example, collection.each(function() { ... }); Inside this function, "this" refers to the iterator object. This is one possible usage.

I personally have used .apply() for implementing a queue of requests - I push an array of arguments into the queue, and when the time comes for executing it, I take an element, and pass it as the arguments for a handler function using .apply(), thus making the code cleaner then if having to pass an array of arguments as a first argument. That's another example.

In general, just keep in mind that those ways to call a function exist, and you may one day find them convenient to use for implementing your program.

Why we need call and apply in javascript?

kongaraju

9,03410 gold badges51 silver badges78 bronze badges

answered Dec 28, 2011 at 18:08

IvoIvo

1,6733 gold badges18 silver badges28 bronze badges

If you have experience with Object Oriented Programming then call and apply will make sense if you compare it with inheritance and override the properties or method/functions of parent class from child class. Which is similar with call in javascript as following:

function foo () {
  this.helloworld = "hello from foo"
}
foo.prototype.print = function () {
  console.log(this.helloworld)
}

foo.prototype.main = function () {
  this.print()
}


function bar() {
  this.helloworld = 'hello from bar'
}
// declaring print function to override the previous print
bar.prototype.print = function () {
  console.log(this.helloworld)
}

var iamfoo = new foo()

iamfoo.main() // prints: hello from foo

iamfoo.main.call(new bar()) // override print and prints: hello from bar

answered Apr 2, 2017 at 12:47

sir4ju1sir4ju1

5433 silver badges12 bronze badges

I can't think of any normal situation where setting the thisArg to something different is the purpose of using apply.

The purpose of apply is to pass an array of value to a function that wants those values as arguments.

It has been superseded in all regular everyday usage by the spread operator.

e.g.

// Finding the largest number in an array
`Math.max.apply(null, arr)` becomes `Math.max(...arr)`

// Inserting the values of one array at the start of another
Array.prototype.unshift.apply(arr1, arr2); 
// which becomes 
arr1 = [...arr2, ...arr1]

answered Feb 10, 2017 at 3:24

Daniel CoffmanDaniel Coffman

1,9673 gold badges26 silver badges34 bronze badges

Why do we use apply in JavaScript?

The apply method is used for allowing a function/object belonging to an object x to be called and assigned to an object y.

When and where do you use call and apply methods in JavaScript?

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.

What is the use of call apply bind?

The call, bind and apply methods can be used to set the this keyword independent of how a function is called. The bind method creates a copy of the function and sets the this keyword, while the call and apply methods sets the this keyword and calls the function immediately.

What is difference between call bind and apply?

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.