Disclaimer: This post will not ruin Game of Thrones for you :)
Call: You can use the .call()
method to invoke a function or bind methods to objects that do not have those methods. The first parameter is what the method being called is being bound to. The other parameters are arguments passed into that method. So it would look something like this:
someMethod.call(what object you want a method to be bound to, parameters of method)
In it's most basic form the .call()
the method simply allows you to invoke a function
function gameOfThrones(){
return 'Jaime Lannister'
}
gameOfThrones.call() // Jaime Lannister
// This is the same as doing
gameOfThrones() // Jaime Lannister
Now that we got that useless method out of the way, let us look at the heart of this built-in JavaScript method.
const jonSnow = {
name: "Jon Snow",
getName: function() {
console.log(this.name);
},
isStillAlive: function(boolean) {
return boolean ? this.name + " is alive" : this.name + " is dead";
}
};
// branStark object does not have the methods the `jonSnow` object has.
// How can we give it those methods?
const branStark = {
name: "Bran Stark"
};
// We just called the getName method on the branStark object
// by binding the getName method from the jonSnow object to branStark
jonSnow.getName.call(branStark); // Bran Stark
// We are binding the isStillAlive method to the branStark object
// the next parameter is the arguement to pass into the method
jonSnow.isStillAlive.call(branStark, true); // Bran Stark is alive
Apply: Apply does the same thing except the arguments passed into the methods are put into an array
// the difference between call and apply is that apply takes
// in an array of parameters
jonSnow.isStillAlive.apply(branStark, [true]); // Bran Stark is alive
Bind: Bind returns a new function with its this
keyword being bound to the argument passed into the method. Bind only does the first part of call()
and apply()
which is the binding. The function is also invoked manually. In apply and call we saw the methods invoked automatically. Here is an example:
// bind does not run the function unlike call and apply.
// It simply returns a new function with a new this context
let isBranStillAlive = jonSnow.isStillAlive.bind(branStark,true);
isBranStillAlive(); // Bran Stark is alive
// or you could do
jonSnow.isStillAlive.bind(branStark, true)(); // Bran Stark is alive
// This will yield the same result as well
jonSnow.isStillAlive.bind(branStark)(false); // Bran Stark is dead
// In these examples, we see that we are manually invoking the functions.
Top comments (2)
Hey man. Your style of explaining is amazing. Very easy to understand! But seems like there is a mistake in your last example.
bind
doesn't take arguments as array. It takes arguments regularly similar tocall
.So, this is wrong:
let isBranStillAlive = jonSnow.isStillAlive.bind(branStark, [true]);
But this is correct:
let isBranStillAlive = jonSnow.isStillAlive.bind(branStark, true);
bind
Cheers
woops. Thank you :)