python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
difference between call and apply javascript

difference between call and apply in JavaScript

What is the difference between call and apply?

CALL  -  

Call a function with the specified arguments. You can use call, if you know how many argument are going to pass to the functions.

APPLY -  

Call a function with argument provided as an array. You can use apply if you don't know how many argument are going to pass to the functions.

Both (call and apply) are using to call a functions.

Here is an advantage over apply and call. The .call() method is little bit faster than .apply() method.

Go to live demo example http://embed.plnkr.co/4Rb8Ur/preview

Example code as given below.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="style.css" />
    <script>
        var var1 = {my: "Obj1" };

        var var2 = {my: "Obj2"};

        function preview(par1, par2) {
            alert(this.my + ' ' + par1 + ' ' + par2);
            console.log(this.my, par1, par2);
        }

        //using call as given below
        preview.call(var1, "First", "Second"); //output: var1 First Second

        //using apply as given below
        preview.apply(var2, ["First", "Second"]); //output: var2 First Second

        //using basic as given below
        preview("First", "Second");//output: undefined "First", "Second"
    </script>
</head>
<body>
    <div>
        <h3>Refresh the page and see the alert result or go to console window and see the result.</h3>
    </div>
</body>
</html>


The output: go to link http://embed.plnkr.co/4Rb8Ur/preview









Thank you!



ANIL SINGH

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions