Importance of Natural Resources

WTF is THIS: Understanding the “this” keyword in JavaScript


In this video we’re going to be talking
about the this keyword in JavaScript so the very first thing to understand when
we’re talking about this keyword is really understand what’s the purpose of
the this keyword is or why we even have the this keyword in JavaScript what did
this keyword allows us to do is it allows us to reuse functions with
different context or in other words it allows us to decide which objects should
be focal when invoking a function or a method so imagine we had one function
and we had a bunch of objects that had similar properties we want that function
to work throughout all of our objects so in this video we’re going to be breaking
down to this keyword into four rules the first year-old is called implicit
binding and then we’ll cover explicit binding new binding and the window
binding now this sounds like a lot but I promise once you kind of get the hang of
it it won’t be too bad the first thing you
need to ask yourself whatever you’re trying to figure out what this keyword
is is this question where is this function invoked because whenever you’re
trying to figure out that this keyword is you have to look at when the function
was invoked not when it was defined specifically when it was invoked so
let’s say we had a function here called say name that took in a name and then
it’s just going to console dot log hello and whatever that name was if I were to
ask you right now what this function is doing and specifically what does it
counsel to log in his name you wouldn’t know because you’re not going to
understand what name is until the function is invoked it’s the exact same
idea with of this keyword we won’t know what that this keyword is in a function
until that function is invoked now let’s go ahead and look at this very first
rule called implicit binding and sosa binding is the most common rule and
it’ll probably be found at about 80% of the use cases when they’re trying to
figure out that this keyword is so that’s what we’re going to cover first
see we had an object called me which had a name and it had an age and this object
also has a same name method on it inside of this method we’re going to
couple that log with that name so now the question is trying to figure out
what this keyword inside of the same function reference as well and plus the
binding says that when you call a function and when the function is
invoked look to the left of the dot and that is what that this keyword is going
to reference so in this case we have our function invocation this is the dot if
we look to the left of the dot me so it’s as if we did meet that name which
is going to give us Tyler so if we vlog this now we get Tyler so let’s take this
one step further and what if we had a same name mixin so this function what’s
going to do is it’s going to take in an object it’s going to add a same name
property onto this object or sating method and then it’s going to do the
same thing in constant log this dot name so now what we can do is if we had let’s
make another me object with a name and an age and then let’s make a new object
with a name and an age now if we go ahead and pass both of these objects
into our mixin it’s going to go ahead and decorate them with a noose a name
property is if we call me dot say name and if we call us a name we’re going to
get two different things because in this invocation means to the left of that and
in this function of location U is to the left of the dot and meet that name is
Tyler and you that name is Joey so let’s see if this works
and there we go Tyler and Joey let’s go ahead and do one more example say we had
a person class and I use that term loosely so we have this function is
going to return us an object and it’s going to return us is an object
with the name property and age property and again I say name method and here if
we come to that log this name now if we create a new instance of this class
let’s say Jim we’re going to go ahead and pass in Jim and pass and 42 so now
when we call Jim’s a name you ask yourself okay what so left the dot Jim
is so it’s going to give us Jim okay but what if we came in here and made this a
little bit more complex what if we came in here and had a new object on this
other object that also had a name property and that also had a same name
property and then in here we complement log this name so now we create Jim and
then we invoke Jim that same name but then we invoke Jim dot mother dot say
name what do we expect this invocation to give us well if we look here’s the
invocation we look what’s to the left of the dot here’s the dot and its mother
and does mother have a name property does which is Stacie so we should expect
to see Stacie there we go now the scene is deceptively easy and because it is
rather straightforward you’re going to find that whenever you get any
situations of trying to figure out what this keyword is the very first thing you
should do is look at when the function was invoked and look if there’s anything
to the left of the dot because if there is that’s what this keyword is
referencing in this video we’re going to talk about
the second rule for figuring out what the best keywords are something and
that’s called explicit binding in the previous video we saw something like
this where we had an object and we can call a method on our object we know that
because Stacey still left the dot Stacey is going to be what this is
referencing inside of this function but what if we did something like this what
if we were to takes a name out of this function so instead of being a method on
the object now it’s just a function currently in a global scope so now what
we want to do is we want to somehow call this function in the context of Stacey
so what we can do is if we type the function name every function has a dot
call property that allows us to do just that so the very first argument that it
takes in is the context that you want to call this function as’ so now what
happens is same name is going to be invoked and the this keyword inside of
say name is going to reference stacey so if we log this we should see my name is
Stacey and there we go so in this example we’re explicitly stating what
this keyword is when we do call and it’s the very first argument that we pass to
our dot column location now let’s go ahead and say that if we wanted to pass
a parameter or pass if you are a few more arguments to say name what we can
do is let’s say we had an array of languages so what we can do here and
call the very first argument you pass it is the context and every argument after
that is going to be passed to the function just as a normal argument so
let’s go ahead and pass in languages a 0 so JavaScript language is at 1 so Ruby
and language is at 2 which will be Python then here let’s just say link 1
link 2 and length 3 so we’re going to log my Navis and whatever the name is
plus and length three so what we’re doing
here is we are invoking say name in the context of Stacy
so we’ll get so it’s as if we’re coming in here replacing this with Stacy and
Stacy that name you know Stacy and we’re passing along three arguments we have
three parameters here so what we should get is my name is Stacy and I know
JavaScript Ruby and Python let’s see if this works
all right perfect so this seems a little counterintuitive so what if we were able
to do something like this it would be nicer if we can just pass in languages
and some feature in the end the language of JavaScript would be able to kind of
parse these out for us and that’s exactly what that apply does so dot
apply is the exact same thing is that call but instead of passing in the
arguments one by one you can pass in an array of arguments and it’s going to
basically parse it for us here so we should get the exact same blog as we did
before with that call because we can now pass in just an array so the very last
thing to look at is this dot buying property dot bind is almost the exact
same thing as call except there’s one thing that’s different so let’s go back
to our code before we had that call so now what we can do is if we change this
to dot bind what’s going to happen is that bind is going to return us a new
function instead of invoking the original function so if we come in here
and do a new function so now instead of invoking same name it’s just going to
bind this to Stacy passing these arguments and then return us a brand new
function which we can call later so if I come in here I’m just going to cancel
that log something right here so we can see that later we’re invoking this new
function and we should get the same output
so to recap call apply and vine allow us to explicitly state what this keyword is
going to be in any given function call and not apply behave the exact same way
they will immediately invoke the function but with dot call you pass in
our you it’s one by one and with that apply you
pass them in as an array and dot bind is the exact same thing as call but except
for immediately invoking the function it’s going to return you a brand new
function that you can invoke later in this video we’re going to talk about the
last two rules for figuring out what this keyword is referencing the first
one is new binding and the last one will be the window binding so you may have
seen this before what we have here is a function we’ve capitalize the first
letter to express that this is going to be a constructor function and that
should be called with the new keyword so let’s go ahead and have this function
take in the color a name and a type and then what we usually do is just go ahead
and add those to this so what happens when this function is invoked let’s make
a new zebra because we’re invoking it with the new keyword what’s going to
happen is behind the scenes here javascript is going to create a brand
new object for us and save it as this so it’s a little bit more fancy than just a
regular object which we’ll talk about in other videos but for now you can think
about that this in here is just an object and so the new binding rule
states that when a function is invoked with the new keyword that this keyword
inside that function is bound to the new object being constructed or the subject
right here and the last rule for trying to figure out what this keyword is
referencing inside a function is window binding so let’s say here we had a say H
function just like we’ve kind of had in the last and last video and all it’s
going to do is console dot log this H so if I had a function what we’d usually do
is if we want it to call say H in the context of me we would have to do a sage
call and pass in me but what happens if we don’t do that what if we just try to
invoke sage and we don’t specify what this keyword is we’re not using call
there’s nothing so away for the dot so let’s see what happens here I’m going to
comment all this stuff out and I run this you’ll notice I get undefined
because what’s happening is if you invoke a function that uses of this
keyword but doesn’t have anything to the left of the dot it’s not using the new
binding and you’re not using call apply or bind then so this keyword is going to
default to the window object so if I come in here and
add a property of age to the window object and then I invoke sage again what
you should see is undefined then I set the age property on window and then it
gives me 35 so probably not the best thing in the world but it’s kind of what
happens in JavaScript what’s interesting though is if I come in here and I run
this function in strict mode basically what strict mode allows us to do is it
allows us to opt into a more strict version of JavaScript now if I go ahead
and try it around say age what happens is again air because strict mode is
smart enough to know that hey you don’t want do what you’re doing you don’t want
the disk keyword to be bound to the window object or to reference the window
object so I’m not going to let you do that
so to recap all our rules we have implicit binding which is you look to
let’s bedad call time explicit binding which is telling a function what the
context of this keyword is going to be using call apply or bind the new binding
is whenever you have a function invoke with a new keyword – this keyword is
bound to new object being constructed and the window binding where if none of
these rules apply then that this keyword is going to default to the window object
unless you’re in strict mode then it’s just going to be undefined


Reader Comments

  1. Thank you so much for this. After watching a similar video where examples were treated with foos and bars, it's great to have more relatable context used in the examples. Subbed!

  2. var likedIt = function () {
    console.log('Thank you for such a nice tutorial ' + this.name);
    }

    var tyler = {
    name: 'Tyler'
    }

    likeIt.call(tyler);

  3. Thanks for this Tyler, I've been looking for a clear explanation on call, apply, and bind for what feels like years. You rock, sir 👍

  4. this video has the best explanation I have seen so far for call, apply and bind built in functions.

    func f1, f2(p1,p2)
    obj o

    since all objects have call, apply or bind functions you can do
    o.call(f1) or o.call(f2, p1, p2) [notice for call() first param is the func name, the rest is params of the func itself]

    apply() is similar to call() but instead of passing function params one at a time you pass in as an array
    o.apply(f2, [p1, p2])

    bind() is similar to call() except bind() returns a func
    func f3 = o.bind(f1) or f4=o.bind(f2,p1,p2)

  5. Hey Tyler, you make really great videos and have a talent for explanation. Thank you for all the hard work!

    Have you considered doing your work in Scrimba instead of jsbin? It helps me to pause and run portions of your code to check my understanding.

  6. After 100s of videos, books, and lectures, now I finally understood WTF is this. Especially that dot before the object. Thanks a lot, mate. Please keep continuing WTF series.

  7. I've been trying to get my head around 'this' this morning and your video is definitely the best explanation I've encountered so far. Thanks.

  8. HEY , what if
    var sayAge = function (){
    var me = {
    age :25
    };
    console.log(this.age);
    };
    sayAge();

    …why does that not work i created an object inside a function and i invoke the function…?

  9. whydoes every youtuber use "this" in their regular vocabulary when talking about thisconcept so annoying

  10. const likedIt = (human) => {
    human.liked = function(){
    console.log(`${this.name} liked your video!`)
    }
    }
    const user = {
    name: 'Jamar'
    }

    likedIt(user);

    user.liked()

    Thanks for clearly showing off the THIS feature! I used a implicit function to describe my like for this

  11. This is the best video that explains the concept. 100% thumbs up. This keyword shouldn't be complex if well explained 🙂

  12. I have seen and heard S..tloads of explanations on "THIS" but this one is by far superior hands up Kudos and stuff.

  13. I almost never subscribe to anything, but you did such a fantastic job explaining such a complex topic, that I chose to go out of my way to subscribe and like this video. Thank you so much, I was never able to understand it until now.

  14. Twice in college professors explained me about this this. I also bought 2 JS courses and I couldn't understand it untill i saw your vid.
    Conlusion: I'm i very slow learner.
    But you also explain like no other, thanks a lot!

  15. Java newbie here! Serious Kudos on this video!! I was ready to crawl into a corner and cry but your explanations were so easy to follow!!

  16. You are best in not making the things complicated yet explains everything in a short span of time . Thank you 👏👏

  17. What a fucking beautiful video! It is THE best video in Javascript available on Youtube! I can finally understand the "this" keyword in my life!!!!!

  18. And this video makes me to buy your react course. Finally I undestand bind, call and apply! How I explain my wife this expenditure..?

  19. This is a really helpful video. The this keyword was initially quite difficult to wrap my head around, but now I have a better understanding of it after watching this video.

  20. 🚀 Try our new 2019 React Course – https://tylermcginnis.com/courses/react/?s=youtube-this-keyword-call-apply-bind-javascript

Leave a Reply

Your email address will not be published. Required fields are marked *