Documente Academic
Documente Profesional
Documente Cultură
Ritik
61
bind in JavaScript + FOLLOW
location
Ritik Apr 19 ・3 min read
India
Before start looking into call, apply, bind you should understand - how does
"this" keyword works in JavaScript. Where the wild code grows
In short "this" creates a reference to an object. It may refer to global object i.e. Sign up (for free)
{window object} in global scope.
console.log(this);
//Window {parent: Window, opener: null, top: Window, length: 4, frames: Window, …}
const student = {
name:"ritik",
getDetails(){
console.log(this);
}
}
student.getDetails();
//{name: "ritik", getDetails: ƒ}
const religion = {
type: "humanity",
property:"greatest"
}
function getDetails(){
console.log(`${this.type} is the ${this.property} religion`);
}
getDetails();
//undefined is the undefined religion
const religion = {
type: "humanity",
property:"greatest"
}
function getDetails(){
console.log(`${this.type} is the ${this.property} religion`);
}
getDetails.call(religion);
//humanity is the greatest religion
getDetails.apply(religion);
//humanity is the greatest religion
Both "call" and "apply" work in the same way but they handle arguments in
different manner.
Now let us pass some parameters to the function "getDetails".
const religion = {
type: "humanity",
property:"greatest"
}
function getDetails(world,creature){
console.log(`${this.type} is the ${this.property} religion in the ${world} of ${creature
}
getDetails.call(religion,"modern world","human");
//humanity is the greatest religion in the modern world of human
getDetails.apply(religion,["modern world","human"]);
//humanity is the greatest religion in the modern world of human
"Bind" method creates a reference of "this" to the object it has been passed
with, same like "apply" or "call" but returns a function.
Now that function can be used multiple times with different "arguments" in
your code.
const religion = {
type: "humanity",
property:"greatest"
}
function getDetails(world,creature){
console.log(`${this.type} is the ${this.property} religion in the ${world} of ${creature
}
If you dont want to store the returning function than, It can be invoked
directly like this:
const religion = {
type: "humanity",
property:"greatest"
}
function getDetails(world,creature){
console.log(`${this.type} is the ${this.property} religion in the ${world} of ${creature
}
getDetails.bind(religion)("modern world","human")
//humanity is the greatest religion in the modern world of human
TheEnd
In this article we learn about call, apply, bind in JavaScript. Try out the code
samples and play with "this" keyword.
{This post is also available on ritikrana.netlify.com}
Ritik + FOLLOW
PREVIEW SUBMIT
Apr 20
Michael Tharrington (he/him)
Love the title! "What the hack" would make for a great series.
3 REPLY
Apr 20
emadsaber
2 REPLY
react-native-web and
monorepo
Bruno Lemos
How to make react-native work in the browser, the right way
553 133
281 19
333 22