Back to Top

Javascript call() and apply()

Updated 26 December 2019

Hey, If you want to learn javascript call() and apply() methods or want to know the differences between both of them then you must read this blog.

Simple object with the method

call2-1

In Javascript, Objects can have methods. If there is a method for which you are not using any object that means it belongs to the “window” object.

The above example will output result “johndoe” because this keyword points to the current object and have properties “firstName” and “lastName”

Now let’s come to call() method part.

Start your headless eCommerce
now.
Find out More

Syntax: obj.callingMethod.call(anotherObject, callingMethodArg1, callingMethodArg2….);

call() method is used for calling any object method with some arguments contains another object along with called function arguments. Please check the following example of call() method

call3

In this example, I just passed another object which is containing the same properties “firstName” and “lastName” so now this refers to the nameObj object in getName() method.

Now let’s see the call() arguments

call4-1

In the upper example, getAddress() function can have two arguments city and country so I can pass calling function arguments as well.

let’s see a different function which returns the only sum of two numbers

call5-1

Here you can see I passed null because in javascript null is also an object. you can console this statement for checking typeof null;

apply() method

Syntax: obj.callingMethod.apply(anotherObject, arrayofArguments);

apply() method is used for calling any object method with some arguments contains another object along with called function arguments as an array.

this method is very similar to call() but the only difference it takes called function arguments as an array instead of passing one by one. Please see the following example of finding maximum or minimum value in an array.

call6

You can practice upper examples of call() method as well.

I hope you had some basic idea of call() and apply() methods. You can now differentiate between call() and apply(). Thanks for your time.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home