Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwivediamit/f05f0f8e2644ea6bafbe5c315b508bcc to your computer and use it in GitHub Desktop.
Save dwivediamit/f05f0f8e2644ea6bafbe5c315b508bcc to your computer and use it in GitHub Desktop.

Difference between call Apply and Bind function in javascript? explain with example

  1) Call invokes the function and allows you to pass in arguments one by one.

  2) Apply invokes the function and allows you to pass in arguments as an array.

  3) Bind returns a new function, allowing you to pass in a this array and any number of arguments.

Apply vs. Call vs. Bind Examples:

1) Call:

        var person1 = {firstName: ‘Jon’, lastName: ‘Kuperman’};
        var person2 = {firstName: ‘Kelly’, lastName: ‘King’};

        function say(greeting) {
        console.log(greeting + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName);
        }

        say.call(person1, ‘Hello’); // Hello Jon Kuperman
        say.call(person2, ‘Hello’); // Hello Kelly King

2) Apply:

        var person1 = {firstName: ‘Jon’, lastName: ‘Kuperman’};
        var person2 = {firstName: ‘Kelly’, lastName: ‘King’};

        function say(greeting) {
        console.log(greeting + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName);
        }

        say.apply(person1, [‘Hello’]); // Hello Jon Kuperman
        say.apply(person2, [‘Hello’]); // Hello Kelly King

3) Bind:

        var person1 = {firstName: ‘Jon’, lastName: ‘Kuperman’};
        var person2 = {firstName: ‘Kelly’, lastName: ‘King’};

        function say() {
        console.log(‘Hello ‘ + this.firstName + ‘ ‘ + this.lastName);
        }

        var sayHelloJon = say.bind(person1);
        var sayHelloKelly = say.bind(person2);

        sayHelloJon(); // Hello Jon Kuperman
        sayHelloKelly(); // Hello Kelly King
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment