Tired of Guessing What 'this' Is Referring To?
Angelika Jarosz
Posted on June 7, 2019
What is this
?
If you are new to JavaScript it is only a matter of time before you run into the concept of the this
keyword. The this
keyword is the JavaScript context object in which the current code is executing. When JavaScript code is executing, it is running within a specific execution context. When a browser first loads a script, it is in the global execution context. However, once a function is called a new execution context is formed and pushed onto the call stack.
At first determining the value of this
might feel a little like magic and have you throwing console.log()
's in your code. However, there are only a few rules that you can go through to figure out what this
is referring to. The most important thing to first remember is that the value of this
depends on how a function is called. Looking at where the function is defined will not help you.
Rules for determining the value of this
:
First we look to see if the new
keyword is used when calling the function. If new
is used this
inside the function will refer to the brand new object created when new
runs Object.Create()
under the hood.
Second we see if apply, call, or bind are used when calling the function. this
inside the function will refer to the object that is passed in as the argument to apply, call, or bind.
Third, if a function is called as a method, such as obj.method() — this
will refer to the object that the function is a property of.
Otherwise this
is the global object. In a browser, it is the window
object. If in strict mode ('use strict'
), this
will be undefined
instead of the global object.
One thing to note is that ES6 arrow functions ignore all the rules above. They do not have their own this
, so this
is determined lexically. This means that JavaScript will look to its surrounding parent scope to determine what this
is referring to.
Why is this
even important?
If we think about why we write functions in general we see that functions make it easy to encapsulate and reuse logic. The this
keyword lets us decide what context we want when we invoke a function. By using this
we can reuse functions or methods within different contexts or with different objects.
If you have any questions, comments, or feedback - please let me know. Follow for new weekly posts about JavaScript, React, Python, and Django!
Posted on June 7, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 25, 2024
October 6, 2024