Simplifying the "this" Javascript keyword
The "this" keyword always refers to an object, but the value of "this" changes depending on where it is called. When a function is called, an execution context is created that contains a reference to "this". Because the value of "this" changes depending on execution context, we can determine the value of "this" by examining the function's call-site, or where it is called.
Conveniently, there are four simple rules to help determine the value of "this"!
Rule #1: Default Binding
When called alone, or within a function, "this" will refer the Global object. In a browser, this will refer to the Window object. One exception to this is if the user is in strict mode, in which case "this" will be undefined.
Rule #2: Implicit Binding
If a function is contained within an object, "this" will refer to the nearest parent object. Even if the function is only referenced in the object, "this" will still refer to the object.
Rule #3: Explicit Binding
There are three functions call, bind, and apply that can be used to set the value of "this". Call and apply work largely the same way, the first argument passed to each will be what "this" refers to. Bind actually creates a new function which a permanently assigned "this" value.
Rule #4: New Binding
When using the new keyword, "this" will refer to the new object that is being created.
The Arrow Function Exception!
One exception to these general rules of thumb is that when using an arrow function, "this" will retain the value of its parent scope.
The Dev Recap:
So a quick summary of the "this" keyword:
- "This" is usually determined by a function's execution context.
- By default, "this" refers to the global object (window object in a browser).
- When the "new" keyword is used, "this" will refer to the new object.
- Call, bind, and apply can be used to set "this" value.
- Arrow functions do not re-bind "this".
Hopefully this is helpful to someone new to Javascript who is trying to wrap their head around the "this" keyword! Thanks for reading and don't forget to follow!!
Top comments (5)
This is a nice and quick reference on
this
for those familiar with it already. It's a great crash course on everything.However, I wouldn't exactly say that this is going to be "helpful to someone new to JavaScript". If I read this when I first started JavaScript, all this jargon and terminologies would blow my mind off of its brain stem (no joke). It is especially intimidating to see those big words for a first-time programmer. Now that I think about it, I do see that the deep vocabulary of the article is completely necessary given the topic. It's just hard to explain the dynamic nature and context-sensitive behavior of
this
. Oh, what a pain it is to teach!Nonetheless, this is a satisfyingly concise article on
this
. Good job!Frankly I really appreciated the meme in the banner image. Cool post!
I wanted to say the same :D
this post really helped! Thanks :)
Obligatory