The call and apply Methods | JavaScript 🔥 | Lecture 124
Summary
TLDRIn this informative lecture, we delve into the intricacies of the 'this' keyword in JavaScript, particularly focusing on how to manually set it and understand its significance in different contexts. Using Lufthansa, the largest European airline group, as an example, we explore creating a simple booking system. We illustrate how the 'this' keyword can dynamically point to different objects, such as Lufthansa and Eurowings, to handle bookings. Through practical examples, we introduce the use of JavaScript's first-class functions and the methods 'call', 'apply', and 'bind' to explicitly set the 'this' keyword, demonstrating how to efficiently manage function contexts across different objects without duplicating code.
Takeaways
- 📚 The 'this' keyword in JavaScript refers to the object it belongs to, and its value varies depending on how the function is called.
- 💻 Enhanced object literal syntax allows for simpler method definitions in JavaScript objects.
- ✈️ Example given involves creating a booking system for airlines like Lufthansa and Eurowings, demonstrating practical use of 'this'.
- 📈 Methods within objects can access the object's properties and array of bookings using 'this' keyword.
- ⚡️ Directly copying methods between objects is discouraged due to bad practice; instead, functions should be stored externally and reused.
- 🔧 JavaScript's first-class functions enable the storage of functions in variables for reuse across different contexts.
- 🔒 Regular function calls set 'this' to undefined in strict mode, illustrating the dynamic nature of 'this'.
- 🔨 The 'call' method allows explicit setting of 'this' for a function, enabling flexibility across different objects.
- 👨🔧 The 'apply' method is similar to 'call', but takes an array of arguments instead.
- 🔫 Modern JavaScript favors the 'call' method with spread operator over 'apply' for passing an array of arguments.
- 🔔 'bind' method offers another way to set 'this' keyword but is left for further discussion in the next lecture.
Q & A
What is the main topic being discussed in this lecture?
-The main topic being discussed is how to manually set the 'this' keyword in JavaScript using the call, apply, and bind methods, and why you would want to do that.
Why is it considered a bad practice to copy and paste methods across different objects?
-It is considered a bad practice because it violates the DRY (Don't Repeat Yourself) principle of programming. Instead, it's better to create a separate function that can be reused across different objects.
What happens when you call a regular function, and how does it affect the value of the 'this' keyword?
-When you call a regular function (not a method), the 'this' keyword inside that function points to undefined in strict mode. This is because the function is not bound to any specific object.
How does the call() method allow you to manually set the 'this' keyword?
-The call() method allows you to manually set the 'this' keyword by passing the object you want 'this' to reference as the first argument. The remaining arguments are passed to the function being called.
What is the difference between the call() and apply() methods?
-The call() method accepts the arguments to be passed to the function individually, while the apply() method accepts an array of arguments to be passed to the function.
How can you achieve the same functionality as apply() in modern JavaScript?
-In modern JavaScript, you can use the spread operator (...) with the call() method to spread the elements of an array as individual arguments, achieving the same functionality as apply().
Why is the bind() method considered more important than call() and apply()?
-The bind() method is considered more important because it allows you to create a new function with the 'this' keyword permanently bound to a specific object, which can be useful in certain scenarios like event handlers or currying.
What are the property names that the 'book' method expects to exist on the airline objects?
-The 'book' method expects the airline objects to have properties named 'airline', 'iataCode', and 'bookings'.
Why is it important to understand the dynamics of the 'this' keyword in JavaScript?
-It is important to understand the dynamics of the 'this' keyword because its value can change depending on how a function is called, and understanding this behavior is crucial for writing correct and maintainable code.
What is the purpose of creating the 'book' function separately and assigning it to a variable?
-The purpose of creating the 'book' function separately and assigning it to a variable is to enable code reuse across different airline objects, rather than copying and pasting the method into each object.
Outlines
🛫 Understanding the 'this' Keyword in JavaScript
This section introduces the concept of using the 'this' keyword within a JavaScript object, focusing on a simple booking system for an airline, specifically Lufthansa. The lecturer demonstrates creating an object with properties like airline name, code, and bookings array, and a booking method using enhanced object literal syntax for simplicity. The method logs booking information to the console, illustrating how the 'this' keyword refers to the object it is part of, allowing access to the object's properties and methods. This is highlighted as a review of how 'this' operates, emphasizing the importance of understanding its behavior before moving on. An example is shown where two bookings are made, reinforcing the idea that 'this' points to the Lufthansa object where the book method is called.
🔄 Reusing Functions with First-Class Functions in JavaScript
This segment explains how to avoid redundancy and bad practices, like copying and pasting methods between objects, by leveraging JavaScript's first-class functions. The instructor illustrates this by extracting the book method from the Lufthansa object and storing it in a separate, reusable function. However, a challenge arises when the 'this' keyword becomes undefined because the method is now a regular function call, not tied to any object. This issue highlights the dynamic nature of 'this' in JavaScript, depending on how a function is called, and sets the stage for discussing solutions to explicitly set the 'this' keyword for different contexts.
🔧 Setting the 'this' Keyword Manually with call and apply Methods
The lecture progresses to solve the problem of the undefined 'this' keyword when calling a function outside of its original object. The instructor introduces the 'call' and 'apply' methods as tools to explicitly set 'this' to a specific object, allowing for flexibility in function calls across different contexts. Examples include booking flights for Eurowings and Lufthansa by setting 'this' appropriately using 'call', demonstrating how it enables the reuse of the book function while correctly associating bookings with their respective airlines. The 'apply' method is also mentioned, with its primary difference from 'call' being the way arguments are passed (as an array), showcasing another method of manipulating 'this'.
🛠️ Advanced Manipulation of 'this' with Modern JavaScript Techniques
In this concluding section, the focus shifts to more advanced and preferred techniques in modern JavaScript for setting 'this'. The lecturer suggests using the 'call' method with the spread operator to distribute array elements as arguments, showcasing its advantage over the 'apply' method in contemporary JavaScript development. This approach simplifies the syntax and improves readability when setting 'this'. The introduction of the 'bind' method is teased as an even more important tool for explicitly defining 'this', promising a deeper exploration in the next lecture. This part solidifies understanding of manipulating 'this' across different contexts and foreshadows the continuation of the topic.
Mindmap
Keywords
💡this keyword
💡enhanced object literal syntax
💡template string
💡function call
💡first-class functions
💡undefined
💡call method
💡apply method
💡spread operator
💡bind method
Highlights
Introduction to manually setting the 'this' keyword and its importance.
Creating a simple booking object for Lufthansa using enhanced object literal syntax.
Explanation of the 'this' keyword within a method, pointing to its own object.
Illustration of adding a booking to the bookings array and logging the outcome.
Introduction of Eurowings as a new airline in the Lufthansa Group, aiming for code reuse.
Storing the book method in an external function to avoid duplication and promote reuse.
Demonstration of 'this' keyword pointing to undefined in a regular function call.
Fixing the 'undefined' issue by explicitly setting the 'this' keyword using the call method.
Using the call method to manually and explicitly set the 'this' keyword for different airlines.
Addition of the Swiss Air Lines to demonstrate setting the 'this' keyword for multiple airlines.
Comparison between the call and apply methods for setting the 'this' keyword.
Introduction of the apply method and its usage with arrays for argument passing.
Highlighting the modern JavaScript practice of using the call method with the spread operator over apply.
Summary of the ability to explicitly define the 'this' keyword in any function.
Teaser for the next lecture on the bind method, which is considered more important than call and apply.
Transcripts
In this lecture,
we're gonna go back to the this keyword
and learn how we can set the this keyword manually
and also why we would want to do that.
So let's say we are an airline again
and in this case, Lufthansa,
which is the biggest European airline group, by the way.
And so let's create a very simple object
for this airline with a very simple booking method as well.
So we have the airline name.
We have the code basically.
We also want to keep an array of bookings.
So also inside of the object,
and then the book method.
And remember from the previous section,
I will now start using the way of writing methods,
using the enhanced object literal syntax.
And so that's simply by defining the method like this
without having to write a function.
So remember, before this,
we used to do this, right?
And if you still prefer this syntax,
you can still do this one.
But I do actually prefer the new syntax.
And so I'll just start using this one now.
So the flight number
and also the passenger name here.
So then let's log something to the console.
And again, this could have been boilerplate code here
but it's also good to practice writing this.
So this should be a template string booked a seat on,
so basically, we want to print like Jonas booked a seat
on Lufthansa flight
and then the flight number.
And so here we are now going to get the airline name
from the object.
And so we already learned
that for that, we use the this keyword, right?
And then flight this.iataCode.
So that's gonna be the LH
and then the flight number itself
that we pass into the function.
So the flightNumber.
So for now, this is just a nice review
of how the this keyword works, right?
And of course, I will now assume that you know
how all of this works
because otherwise, I will have to explain the same things
over and over again.
And so as I mentioned before,
you should only progress once you really understand
a certain topic.
Anyway, let's now use the book function here.
And I'll use the flight number 239
and then with my own name.
And let's right away book another Lufthansa flight
for let's say Mike Smith on flight number 635.
John Smith.
And now, if we take a look at the results,
then indeed, everything works just as expected, right?
And so it's important to understand
that the this keyword here points
to the lufthansa object itself
because that's the object
on which the book method here was called.
So again, that's just what I explained before, right?
But now let's say that after some years,
the Lufthansa Group created a new airline.
So let's create eurowings here.
And then a very similar object.
So with the airline, the code.
And also an empty bookings array.
Okay?
Oh, and by the way,
we actually also want our book method here
to add a new object to our bookings here.
So that's super important as well.
So I forget that.
So let's go back here.
So we will say again this
and then the bookings array
and then let's put a new object in there
with the flight
and so that's essentially gonna be this one.
So the code plus the flight number.
And then also the passenger name.
And then let's quickly log that to the console here.
So this.bookings is not a function
and of course, it's not.
We need the push method indeed.
And so now you see that we have an array
of our two bookings here.
So that works perfectly.
But now anyway, going back here to Eurowings,
of course, we also want to be able
to take bookings for a Eurowings flight,
so as being this airline, right?
Now, taking this exact same method here
and simply copying it and pasting it here
is a bad practice, right?
So of course, we are not gonna do that.
So instead, we will just take the method
and store it in an external function.
And then we can reuse that function
for all of the different airlines.
So what I mean is to create a new function called book
and we will simply set it to lufthansa.book, all right?
So again, this is possible
because JavaScript has first class functions.
And so we can simply take this function value here.
So that's this function
and then store it into a new variable,
which is then gonna be also the book function, okay?
Now, we could have written the function here also literally
but that's just not necessary.
We have it right here
and so let's just leave it there
and assign it to book right here.
Okay, so let's try to use this book function
to do a new booking now.
But what do you think is gonna happen?
So 23, and then let's say Sarah Williams
and let's give it a save
and now we get cannot read property airline of undefined.
So do you know why this happened?
Well, it's because this function here,
the book function is now just a regular function call
and so as we learned in one of the previous sections,
in a regular function call,
the this keyword points to undefined,
at least in strict mode.
All right?
So once more, this book function is no longer this method.
Okay?
It's just not.
It is now this separate function here.
It's a copy of this one
but it's not a method anymore,
it's now a function.
And so here it's a regular function call.
And so therefore, the this keyword inside of it
will now point to undefined.
And that's why I kept telling you earlier
that the this keyword depends on how the function
is actually called.
Okay, so make sure to understand these dynamics here.
But now how do we actually fix this problem?
So in other words, how do we tell JavaScript
that we want to create a booking
on the new Eurowings airline?
Or even how do we tell it that we want
to book on Lufthansa here?
Well, basically, we need to tell JavaScript explicitly
what the this keyword here should be like.
So if we want to book a Lufthansa flight,
the this keyword should point to Lufthansa
but if we want to book a Eurowings flight,
then the this keyword should point to Eurowings.
So how do we do that?
How do we tell JavaScript explicitly
or manually what this this keyword should look like?
Well, there are three function methods to do that
and they are call, apply and bind.
So when we first talked about the this keyword,
I think I mentioned these methods back then
and so now we're gonna use them,
at least the call and apply methods.
Okay, so let me show you how.
So instead of just doing this,
which doesn't work,
let's actually comment that out.
Does NOT work.
So instead, we use book.call, all right?
And remember that a function is really just an object
and objects have methods
and therefore, functions can have methods too
and the call method is one of them.
And in the call method,
the first argument is exactly
what we want the this keyword to point to.
So let's say we want a Eurowings flight
and then as usual,
the rest of the arguments.
So 23 and Sarah Williams.
All right?
And then let's log to the console also the eurowings object.
Let's run this and then I'll explain a bit better
what just happened.
But indeed, we now have the bookings array
and in there, we have the object
with the EW23 and so EW comes from here.
So exactly from the eurowings object
and then also, of course, the name.
And again, it is inside the bookings array
of the Eurowings object.
So let's recap what happened here.
So this time, we did actually
not call the book function ourselves.
Instead, we called the call method
and it's then this call method,
which will call the book function
with the this keyword set to eurowings.
So whatever we pass has the first argument
of the call method.
And so this allows us to manually
and explicitly set the this keyword
of any function that we want to call.
Then all the arguments after the first one
are simply the arguments of the original function.
And so in the case of the book function,
of course, that's the flight number
and the passenger name.
And of course, now we can do the same also for Lufthansa.
So book.call, this time with lufthansa
and let's book someone else on flight 239.
Let's say Mary Cooper
and let's log again the lufthansa object
but let's do it now here.
And indeed, the string that we get here
is completely correct
and in here, so in the Lufthansa bookings array,
we now have, of course, three bookings.
Okay?
And so that, of course, happened because this time,
we set the this keyword inside
of the function call to lufthansa.
And so now this here is again back to pointing to Lufthansa,
while before, right here,
it was being pointed to Eurowings, all right?
So even though the code of this function
is inside of the lufthansa object,
we made it so that the this keyword in here
pointed to eurowings.
So to this object, this new one right here, okay?
So we have a way now
of manually manipulating the this keyword
using the call method.
And of course, we could now keep going
and create more airlines into the Lufthansa Group,
like the Swiss Air Lines.
Air Lines.
Now, of course, these property names,
they all need to have the exact same format
as this original object here
because this method is trying to read just these properties.
So it's always iataCode
and bookings, as you see here, and airline.
And so of course,
we need to use exactly these property names here as well
but just like this,
we can now go ahead
and use our book function on the Swiss Air Line.
And so this time, we will set the this keyword
in the book.call to the swiss object.
583 and let's book another flight for Mary Cooper here.
And indeed, it worked again.
So here is the booking again.
Okay?
There's just some weird thing here
and so oh, actually here,
it needs to be airline as well.
So I was telling you you need to use the same property names
and I wasn't even doing it myself.
So it needs to be airline, just like it is here
and the same here too.
And now the string is, of course, correct here.
Okay.
Let me add a comment here.
Call method because in fact,
there is a similar method to the call method,
which is called the apply method.
And the apply method does basically exactly the same thing.
The only difference is that apply
does not receive a list of arguments
after the this keyword,
so it doesn't receive this list here
but instead, it's gonna take an array
of the arguments, okay?
And so it will then take the elements
from that array and pass it into the function.
So let's say
flightData,
so I'm just gonna create quickly an array here
with the flight number and the passenger name.
So book on the same flight George Cooper
and now we can use apply on the book function.
So apply.
And then just as here in the call method,
the first argument is the this keyword.
But now the second argument,
it needs to be as I just said an array of data.
So let's pass in the flightData array here.
But then let's just take a look.
I'll just take this one here actually.
And so indeed, here it worked again.
All right?
This apply method is not that used anymore
in modern JavaScript because now,
we actually have a better way of doing the exact same thing.
And do you know what I'm talking about?
So let me show it to you.
Book.call, so instead of using apply,
we can still use call,
again with swiss
and then we can simply use the spread operator
to take the data out of flightData
and basically put them here.
So this here is the same as this one.
And so right now, with modern JavaScript,
I prefer to just always use the call method
and then spread out the arguments from an array like this.
So again, this here is exactly the same as this.
So in summary, we now have yet another tool
in our toolbox here
and this one is one that allows us
to explicitly define the this keyword
in any function that we want.
But there is actually yet another method
which allows us to do the same thing
and that's the bind method.
It's more important actually
than the call and apply methods,
so I'm gonna leave it for the next lecture.
Browse More Related Video
![](https://i.ytimg.com/vi/y25hW56-azw/hq720.jpg)
The bind Method | JavaScript 🔥 | Lecture 125
![](https://i.ytimg.com/vi/3a0I8ICR1Vg/hq720.jpg)
Learn Closures In 7 Minutes
![](https://i.ytimg.com/vi/ooCwXobbiiI/hq720.jpg)
LEARN PHRASAL VERBS IN ENGLISH / PASS IT ON / PASS ON IT / LEARN AMERICAN ENGLISH / AVOID MISTAKES
![](https://i.ytimg.com/vi/I848HdWjLMo/hq720.jpg)
La Lógica de la Programación Orientada a Objetos explicada con Minecraft
![](https://i.ytimg.com/vi/MQeVEQU0X6g/hq720.jpg)
Object Methods | JavaScript 🔥 | Lecture 041
![](https://i.ytimg.com/vi/1H7kmNfp3fo/hq720.jpg)
State Update Batching in Practice | Lecture 133 | React.JS 🔥
5.0 / 5 (0 votes)