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
// 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");