DEV Community

Aliya Lewis
Aliya Lewis

Posted on

What's 'this'?

Over the past few weeks, I've been learning tons about JavaScript and React. Between the two of them, I find myself confused and also very clear about what the keyword this is. In React, I feel pretty good about using it and understanding what it's doing but in JavaScript? Ehhh, not so much. To try and make sense of it, I decided to do some research on this in JS.

Alt Text

The first place I looked was the MDN documentation which has this to say:

"In most cases, the value of this is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time a function is called."

That was a little vague so I kept looking. This is what W3Schools says:

Alt Text

Hmm...okay, that makes sense but I'm more of an auditory/visual learner so my next step was to watch videos on YouTube. I came across a couple of videos that I found very helpful and below are a list of things that I found to be the most informative.

Implicit Binding

Implicit binding tells the function to look to the left of the dot to the object it was called on and have this reference that object. Here's an example:

Alt Text

In the above example, we look to the left of the speak function to identify the object that this will reference. We see that the object Jak has a name property that this is attaching itself to, it's implicitly bound because the function that it's created in is inside of the object it's attaching to. Pretty simple right? Great, so now let's dig a little deeper.

Explicit Binding

There are three ways to explicitly bind this in JS, with call(), apply(), or bind(). call() tells the function which object to attach to and can accept additional arguments, like elements in an array. apply() is similar to call() in that it takes in an argument of an object to attach to but instead of passing elements in an array, you can pass the whole array in as an argument. Last but not least is bind(). bind() is also similar to call except that it returns a new function instead of invoking the original function. Below are some examples of each.

call()

Alt Text

apply()

Alt Text

bind()

Alt Text

I hope that this helps someone out as much as it's helped me! For more in-depth explanations, I highly recommend watching the YouTube videos I've linked below. Do you have some good ways to explain what this is? Let me know in the comments!

Sources:

Top comments (0)