Skip to content

Instantly share code, notes, and snippets.

@anushka-beri
Last active April 6, 2021 05:08
Show Gist options
  • Save anushka-beri/22b2d0c15f4b82c59f86f0bcb0bed730 to your computer and use it in GitHub Desktop.
Save anushka-beri/22b2d0c15f4b82c59f86f0bcb0bed730 to your computer and use it in GitHub Desktop.

Call, Apply Methods

var pokemon = {
  firstName: "Pika",
  lastName: "Chu ",
  getPokeName: function () {
    var fullName = this.firstName + " " + this.lastName;
    return fullName;
  },
};

var pokemonName = function (snack, hobby) {
  console.log(this.getPokeName() + " loves " + snack + " and " + hobby);
};

pokemonName.call(pokemon, "sushi", "algorithms"); // Pika Chu  loves sushi and algorithms
pokemonName.apply(pokemon, ["sushi", "algorithms"]); // Pika Chu  loves sushi and algorithms

Bind Method

 // The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

var pokemon = {
  firstName: "Pika",
  lastName: "Chu ",
  getPokeName: function () {
    var fullName = this.firstName + " " + this.lastName;
    return fullName;
  },
};

// var pokemonName = function () {
//   console.log(this.getPokeName() + "I choose you!");
// };

// var logPokemon = pokemonName.bind(pokemon); // creates new object and binds pokemon. 'this' of pokemon === pokemon now

// logPokemon();
// new instance of pokemonName is created and it binds "pokemon" as it's "this" variable. **Note - It copies the pokemonName function.
// After creating a copy of the pokemonName function it is able to call logPokemon(), although it wasn’t on the pokemon object initially.

// And the cool thing is, after we bind() a value we can use the function just like it was any other normal function. We could even update the function to accept parameters, and pass them like so:

var pokemonName = function (snack, hobby) {
  console.log(this.getPokeName() + "I choose you!");
  console.log(this.getPokeName() + " loves " + snack + " and " + hobby);
};

var logPokemon = pokemonName.bind(pokemon); // creates new object and binds pokemon. 'this' of pokemon === pokemon now

logPokemon("sushi", "algorithms");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment