Skip to content

Instantly share code, notes, and snippets.

@codebanesr
Last active June 3, 2020 21:04
Show Gist options
  • Save codebanesr/aba4f1b3674e03f110da7109c09ce092 to your computer and use it in GitHub Desktop.
Save codebanesr/aba4f1b3674e03f110da7109c09ce092 to your computer and use it in GitHub Desktop.

Please go through the post of bind before proceeding, this article will make much more sense. The difference between bind and apply is apply doesnot return a new function, it instantly calls the function that is being bounded to the object.

Here is the object we will be using for demonstrating the use of apply

var object = {
  firstName: "pika",
  lastName: "chu",
  
  getPokemonName: function(){
    let fullname = this.firstName+" "+this.lastName;
    return fullname;
  }
}

The function that will bind the object above, this function doesnot know what getPokemonName is, that is defined in the object, so if we run pokemonEatingHabbits(), it will result in undefined i choose you

var pokemonEatingHabbits = function(snack1, snack2){
  console.log(this.getPokemonName() + " I choose you");
  console.log(this.getPokemonName() + " eats " + snack1 + " and " + snack2)
}

First parameter defines the scope of the function and the second one provides the parameter. So its a way of attaching functionality to object.

pokemonEatingHabbits.apply(object, ["cheeze", "onions"]);

The major difference between apply and call is that, apply accepts an array whereas call takes parameters. Here's an example

pokemonEatingHabbits.apply(object, arrayOfArgs)
pokemonEatingHabbits.call(object, arg1, arg2, ...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment