Menu Close
    Start a Project Request quote Reading list Switch to dark mode
    hyperlocal-marketplace-guide

    Javascript call() and apply()

    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

    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.

    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

    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

    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

    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.

    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.

    . . .

    Comment

    Add Your Comment

    Be the first to comment.

    Back to Top
    css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close