The bind Method | JavaScript 🔥 | Lecture 125
Summary
TLDRThis video tutorial delves into JavaScript's bind method, which, unlike the call method, does not immediately invoke a function but returns a new function with 'this' keyword bound to a specified value. Using an airline booking example, it demonstrates how bind can simplify repetitive function calls by presetting 'this' to Eurowings, enabling easy flight bookings across different airlines. The video further explores partial application, showing how bind can predefine certain arguments for functions, such as specific flight numbers, thereby simplifying the function's usage. Additionally, it touches on the use of bind with event listeners and introduces the concept of creating functions that return other functions for advanced use cases.
Takeaways
- 🔑 The bind() method allows you to set the 'this' keyword for a function and returns a new function with that 'this' value bound.
- ➡️ Unlike call(), bind() does not immediately invoke the function; instead, it returns a new function with 'this' bound to the provided value.
- 🛫 bind() can be used to create function shortcuts for specific objects, like bookEW for Eurowings airline.
- 📋 With bind(), you can also pre-set arguments for a function, a technique known as 'partial application'.
- ⚡ bind() is especially useful when working with event listeners, where 'this' refers to the element the listener is attached to.
- 🔄 By binding the correct 'this' value, you can ensure methods have the intended context when called in event listeners.
- 🧩 Partial application allows you to create specialized functions from more general ones by pre-setting some arguments.
- 🏭 bind() can be used for partial application even when you don't care about the 'this' value (by passing null).
- 🔄 Returning a function from another function is an alternative technique to achieve partial application without using bind().
- 🚀 Mastering bind() and partial application unlocks powerful ways to create specialized, context-aware functions in JavaScript.
Q & A
What is the main difference between the bind and call methods in JavaScript?
-The main difference is that the call method immediately invokes the function with a specified this value and arguments, while the bind method returns a new function with a predefined this value and can include predefined arguments.
What is the purpose of using the bind method in JavaScript?
-The bind method is used to create a new function where the this keyword is set to a specific value, and it can also predefine arguments for the function. This is useful for setting the context of 'this' and for partial application of function parameters.
How does the bind method work with arguments in JavaScript?
-The bind method allows you to not only set the this value but also to preset arguments for the function. These preset arguments are fixed when the new function is created, and the function will always be called with these arguments.
Can you explain partial application with an example from the script?
-Partial application is when some arguments of a function are preset. For example, creating a bookEW23 function that is a specific instance of a book function with the flight number 23 preset. This results in a new function that only requires the passenger name as an argument.
Why does the script use bind in the context of an event listener?
-The script uses bind in an event listener to set the this keyword to a specific object (Lufthansa in the example) instead of the default this value (the button element), ensuring the function uses the correct context when invoked as an event handler.
How is the bind method used to solve the 'this' keyword issue in event listeners?
-Bind is used to return a new function with the this keyword set to the desired object. In event listeners, this ensures the function called as the event handler references the correct object instead of the DOM element that triggered the event.
What is the significance of null in the addTax.bind call in the script?
-Null is used as the first argument in the addTax.bind call because the function does not use the this keyword. It's a convention to pass null when the this value is irrelevant, allowing the focus to be on presetting the subsequent arguments.
How does the script demonstrate the use of bind for simplifying repetitive tasks?
-The script shows that by using bind to create new functions with preset parameters, such as airline or flight number, repetitive tasks like booking for specific flights or airlines can be simplified, avoiding the need to repeatedly set these parameters.
What is the concept of partial application as demonstrated in the script?
-Partial application, as demonstrated, involves creating a new function by presetting some of the original function's arguments, such as setting the flight number or tax rate in advance. This results in a function that requires fewer arguments in future calls.
How does the script illustrate the flexibility and power of the bind method in function customization?
-The script illustrates the flexibility and power of bind by showing how it can create more specific versions of a general function through partial application, such as presetting the flight number or tax rate, making the function simpler and tailored for specific uses.
Outlines
🔍 Exploring the Bind Method and Partial Application
This paragraph introduces the bind method, which allows manually setting the 'this' keyword for a function call. Unlike call, bind does not immediately call the function but returns a new function with the 'this' keyword bound. The paragraph demonstrates using bind to create airline booking functions with preset 'this' values. It further explores partial application, where arguments can be preset in the bind method, simplifying subsequent function calls.
🖱️ Using Bind with Event Listeners
This paragraph explains how the 'this' keyword in an event handler function points to the element the handler is attached to, causing issues when accessing object properties/methods. It demonstrates using bind to manually set the 'this' keyword to the desired object, ensuring correct behavior when handling events on DOM elements bound to object methods.
💰 Calculating Tax with Partial Application
This paragraph introduces a use case for partial application with the bind method, unrelated to the 'this' keyword. It creates a general function to calculate tax on a value and then uses bind to create a new function with the tax rate preset, simplifying subsequent calculations for that specific rate.
🎯 Implementing Partial Application Without Bind
This paragraph challenges the viewer to reimplement the tax calculation example from the previous paragraph using the technique of one function returning another function, instead of relying on bind. It provides a solution demonstrating how to create a higher-order function that returns a new function with the tax rate preset.
📋 Concluding Remarks
The final paragraph concludes the discussion on the bind method and partial application, acknowledging the advanced nature of the concepts covered. It also mentions an upcoming coding challenge related to the topics discussed in this section.
Mindmap
Keywords
💡bind()
💡this keyword
💡Partial Application
💡Higher-Order Functions
💡Callbacks
💡Event Handlers
💡Arrow Functions
💡Closures
💡First-Class Functions
💡Method Chaining
Highlights
bind also allows us to manually set this keyword for any function call, but unlike call, it does not immediately call the function. Instead, it returns a new function where this keyword is bound to the value passed into bind.
By binding the book function to the Eurowings object, we create a new bookEW function that automatically has its this keyword set to Eurowings, simplifying function calls.
bind allows presetting some arguments, creating a partially applied function like bookEW23 that only needs the passenger name, as the flight number is preset.
Partial application, where some arguments are predefined, is a common pattern enabled by bind.
bind is useful when using objects with event listeners, as the this keyword inside the listener refers to the element the listener is attached to, not the object.
Using bind on the event listener function allows manually setting the this keyword to the desired object.
bind can be used for partial application even when the this keyword is not involved, by passing null as the first argument.
An example shows creating an addVAT function by binding the tax rate argument, resulting in a function that calculates VAT for any value passed.
The order of arguments in bind is important when partially applying arguments.
Partial application using bind creates a new, more specific function based on a general function, differing from default parameters.
A challenge asks to rewrite the addVAT example without using bind, by having one function return another function.
The solution involves an outer addTaxRate function that takes the rate, and returns an inner function that takes the value and calculates tax.
This approach separates defining the rate from calculating the tax, similar to the bind implementation.
The transcript notes that this functional programming technique is advanced.
The transcript concludes by mentioning an upcoming coding challenge related to the section's content.
Transcripts
So let's know, learn about the bind method.
And just like the call method,
bind also allows us to manually set this keywords
for any function call.
Now, the difference is that bind
does not immediately call the function.
Instead it returns a new function
where this keyword is bound.
So it's set to whatever value we pass into bind.
So let's continue with our airline example
from the previous lecture here.
And now let's say that we need to use the book function
for Eurowings all the time.
So, remember we have this Eurowings object
and then we used a book.call,
to use the book function
with Eurowings set to this keyword.
So that's what we did in the last lecture.
So let me just copy this code here.
But now, as I said,
we can use the bind method to create a new function
with the this keyword also set to Eurowings, all right?
So again, this will not call the book function.
Instead it will return a new function
where this keyword will always be set to Eurowings.
And so let's create a new function here called bookEW,
where its just a code of Eurowings.
All right?
And so now let's use this function.
So bookEW, Steven Williams
and we're missing the flight number here.
So 23.
And so as you see, this now looks
like the normal book function call again.
And that's because this function here
already has the this keyword set in stone basically.
And so here, of course, we no longer need to specify
to these keywords again.
So the signature here, so the name of the parameters
is back to being simply the flight number
and the passenger name, okay?
And so now again, we see that Steven booked a seat
on Eurowings flight EW23.
And so that worked perfectly.
Let's also of course, see at the object again.
So with all the bookings and indeed here is Steven Williams
in the flight that we just booked.
Great, so this is really, really useful.
And we could now of course go ahead and do the same
for all the airlines.
So creating one booking function for each of the airlines.
And this then makes it a little bit easier
to book a flight for each of the airlines,
if we have to do it multiple times.
So instead of having to use a call all the time,
we can just do bind once.
So defining the disk keyword once like this
and from there on, we can always use these functions.
.bind and this one, Swiss, all right?
Now, I'm not gonna use them all here now
because we already know how that works,
all right?
So this is great,
but we can actually take this even further.
So in the call method, we can pass multiple arguments here
besides this keywords, right?
And so in the bind method, we can actually do the same.
And then all of these arguments
will also be basically set in stone.
So they will be defined
and the function will then always be called
with these same arguments.
For example, we could use bind to create a function
for one specific airline and a specific flight number.
So let's say, bookEW, just like we had here,
but then really specific, only for flight 23.
So that would be book.bind
and then of course we have to again, define Eurowings,
but then we can start to finding the list of arguments
or the list of parameters
and setting the first one to 23, okay?
And so if we look at our bind function now,
remember that it needs the flight number and the name.
But now in our bookEW23 function,
it is as if this first argument was already set.
And so all remaining function now only need the name.
So this function,
this one now only needs the name,
because the number was already preset here
in the bind method.
So, let's see.
So, our newly created function bookEW23,
and let's now book a flight for myself.
And let's book a flight for Martha,
let's say, Cooper.
And, yeah, let's check out our output here.
And so these are the two.
And indeed both of them are for Eurowings flight EW23,
all right?
And so that's exactly what we were expecting.
Again, because we preset that 23 right here.
If we preset this here
to one, two, three, four, five,
then of course, both of these new flights here
would be booked onto that flight number, okay?
So this allows us to set in stone, certain arguments.
And so this function, the resulting function,
then becomes even simpler.
So right now all we need to pass in
is the passenger name, right?
And then everything else basically happens automatically.
And taking this even further,
we could even define, have the passenger name here
for example, like this.
And then this function would always book a flight for Jonas
on flight 23.
But that would probably take it a little bit too far now.
And I deleted the 23 here,
of course, I didn't want that.
So this is correct.
And by the way, what we did here,
so, basically specifying parts of the argument beforehand,
is actually a common pattern called partial application.
So essentially, partial application
means that a part of the arguments
of the original function are already applied,
so which means, already set.
And so that's exactly what the bookEW23 function is, right?
It's essentially the book function
but with 23 already predefined.
Great.
So, hopefully this was a nice example for you to understand
the call apply and bind methods,
but there are also other situations
in which we can use the bind method
and where it is very useful.
And one example of that is when we use objects together
with event listeners.
So let's write that here actually,
with event listeners.
And so now this button here
will finally come into play.
And maybe you've been wondering about that.
But let's start by adding a new property
only to the Lufthansa object
and let's set it to 300.
So meaning that this company has 300 planes.
And then we also add a new method
only to the Lufthansa object,
which is to buy a new plane.
So function,
and now what we want to do is, this.planes++.
So essentially we want to add a new plane,
whenever we click on this button.
So eventually that's what we will want to do.
And then let's also log this.planes to the console.
And probably we should also log this keywords
to the console as well.
And now let's actually attach our event handler
to this element,
let's inspect it here, okay?
It should need to go to elements.
So, this is the button here
and it has the class, buy.
So document.queryselector.buy,
addEventListener for click.
And then the second argument,
as you already know, is the handler function.
So addEventListener here is the higher order function
which receives a callback function.
And so that should be lufthansa.buyPlane, all right?
So essentially, this function here
is what we want to happen,
which again takes the current number of planes
and increases it by one.
So let's do that.
And now as I click on this button, let's see what happens.
And we get not a number here.
So this .Planes is now not a number.
And the reason for that is that this keyword
is this button element, okay?
And do you know why that is?
Well, in one of the theory lectures,
we learned that in an event handler function,
that this keyword always points to the element
on which that handler is attached to.
So, this is the handler function, right?
And so it is attached to this element,
so to this button.
And therefore, inside of the handler function
or the event listener, it doesn't really matter.
But inside of this function,
this keyword will point to the button element.
And so that's why this keyword here
returns this button, okay?
So here you have yet another proof
that this keyword really is set dynamically.
Because if we simply called a Lufthansa.buyPlane out here,
then of course, this keyword would be Lufthansa,
so this object, right?
Because that's the object calling the function.
But in this case it is of course,
this event listener function calling this function.
And so therefore, the button itself
will then become this keyword, okay?
Here we now see the results
of calling this function out here.
And so now we started with 300
and it was increased just as we wanted it to be.
So let's take this out here
and let's go back to clicking here
to see the result we had before.
So that's this button.
Now, of course, in this handler function here,
we still need this keyword to point
to the Lufthansa object itself, right?
Otherwise this logic here will not work.
So what this means is that we need to manually define
to this keyword right here.
So right here.
Now, how should we do that?
Should we use the call method or the bind method?
Well, we need to pass in a function here
and not to call it.
And so we already know that the call method
calls the function.
And so that's not what we need.
And so therefore, we use bind.
Because we already know that bind
is gonna return a new function.
And so this keyword should be Lufthansa,
and so that's exactly what we define, okay?
And now as we click here we should see the Lufthansa object
being this keywords.
Indeed, and that's now exactly what we got here.
So that's the result of this line of code.
And so again, this now points to Lufthansa,
because that's what we told JavaScript to do right here.
And so indeed now the number of planes
is increasing each time that we click on this button.
Great, so we have our problem solved.
And in fact, we will do this a couple more times
throughout the course.
So this one is an important one.
And in general, the bind method
is something you really need to understand, all right?
Now, just one final example here,
which is again, gonna be about partial application,
because this is another big use case for the bind method.
And in this case of partial application,
many times we are not even interested in this keywords,
but we still use bind for this, all right?
Now, remember that partial application
means that we can preset parameters, all right?
So let's start by creating a general function
which adds a tax to some value.
So let's start with the tax rate and then the value itself.
And let's write an arrow function here.
And so this works by doing
value + value * the tax rate, right?
So imagine that the tax rate would be 10%
and the value 100.
And so adding the tax to 100 would be 110.
Well, let's actually do 200 to make it a bit more clear.
And of course we need to call the function here itself,
okay?
So now 10% of 200 is 20,
and so the results should be 220 and that didn't work.
And yeah, that's because we need to define this here
as a decimal number here of course.
So only then this rate here can make sense, okay?
So 220 now.
So this here is the general function for adding tax.
But now let's say that there is one tax
that we use all the time.
And so let's create a function for that.
So for example, here in Portugal,
the VAT, which is value added tax, is 23%.
And so we can now use the bind function
on this function and preset the rate always,
so that it always will be this 23%.
And then we have a function
which only calculates the VAT
for whatever value we pass into it.
So, addTax.bind
and then the first argument of bind
is this keywords, remember?
But in this case, we don't care
about the this keyword at all.
It's not even here in the function.
And so, we just say, null.
It could be any other value
because nothing will happen with it,
but it's kind of a standard to just use null.
And now we can set the rate here.
So let's preset it to 23%,
so 0.23, all right?
And so this sets the rate value here in stone.
So essentially, this would be the same
as writing...
Let's paste it here.
So this must be, addVAT equals,
and the rate is preset to 0.23.
So this is essentially what our addVAT function
now looks like, okay?
So, because we already set 0.23 in stone.
So, now we can start using that.
So this should be 123 and it is.
We can use anything we want now like 23
and so on and so forth.
So I hope this makes sense.
When you want to do this yourself,
just keep in mind that the order of the arguments then
is important.
If you want it to preset the rate,
then it has to be the first argument in this function.
Otherwise, this will not really work here, okay?
Now you could argue that what we just did here
could easily have been done with default parameters.
But this is actually different,
because this here is creating a brand new,
simply, more specific function
based on a more general function,
which is the addTax function.
And of course, the example here
could be a lot more complex too, right?
So this really is different
because using binds,
actually it really gives us a new function.
So, it's as if we returned a new specific function
from the addTax function.
And actually now I have a nice challenge for you
which is to essentially rewrite this whole example here,
but using the technique of one function
returning another function.
So we have one lecture about that
and maybe you can go back and take a look at that.
And then I want you to essentially,
create a function that can return a function
which will do just what this one does.
So that's probably really challenging.
So don't beat yourself up if you cannot do it.
I know it is a challenge,
but you can still try to take a minute or two
and, yeah, really try it.
If you can't do it,
then just watch the solution in a minute, okay?
Just don't use bind of course,
because with that we already have the solution.
So use the technique that I showed you earlier
with the grid function, remember?
And so here you can do something similar.
So, see you in a second with the solution.
Alright.
I hope you tried that out.
And here is how I would have done it.
So, the first function here,
I'm gonna call it addTaxRate.
And I could do this with the arrow functions,
but then that looks really confusing.
So let's just focus on the functionality here.
So this is the first function which only receives the rate.
So similar to what we did here.
And then what it does is to return a new function.
And then this new function
is the one that takes in the value.
And it will then return just as the other function,
value + value * the rate, okay?
And so now based on this one,
we could create addVAT2.
And so that would be, addTaxRate
and then call it with 0.23.
And then let's just do the same
to see if the results are the same.
So, VAT2, and two, give it a try and here you go.
So the results are the same.
And so this addVAT2 is the same function as this one.
So just to recap, we created this function,
which then returns this one.
So the first one is the one that needs the rate,
because the rate is also what we used
to define this addVAT function here, right?
And so the resulting function
is then the one who takes in the value.
And that's why we have value here in the inner function too.
Now this is just another way of doing the same thing
and this is already pretty advanced stuff really.
So, absolutely don't be upset
if you didn't do this by yourself.
But anyway, in the next video
we have coding challenge number one
of this section coming up.
And so I hope to see you there very soon.
5.0 / 5 (0 votes)