What is "this" in Javascript

Onur Demirtaş
October 9th, 2020 · 4 min read

Unfortunately “this” in Javascript is hard to understand. However shortly we can say that “this” is the object that “owns” the JavaScript code. What does that mean? Let’s try to explain it this way: “this” refers to the object that called the function.

Let’s give an example:

1const foo = {
2 name: "foo",
3 log: function(){
4 console.log(this.name);
5 }
6}
7
8const bar = {
9 name: "bar"
10}
11
12bar.log = foo.log;
13bar.log();

Here bar.log has the reference of foo.log and “this” inside the log function refers to the bar object’s scope. Therefore output will be “bar”.

In addition it is really important to understand these rules:

  1. If the new keyword is used when calling the function, this inside the function is a brand new object.
  2. If apply, call, or bind are used to call/create a function, this inside the function is the object that is passed in as the argument.
  3. If a function is called as a method, such as obj.method() — this is the object that the function is a property of.
  4. If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, 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.
  5. If multiple of the above rules apply, the rule that is higher wins and will set the this value.
  6. If the function is an ES2015 arrow function, it ignores all the rules above and receives the this value of its surrounding scope at the time it is created.

You can find the details on this web page:

https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3

Let’s give an example about the difference between normal functions and arrow functions regarding “this”:

1window.name = "global";
2
3const person = {
4 name: "jason",
5
6 shout: function () {
7 console.log("my name is ", this.name);
8 },
9 shout2: () => {
10 console.log("my name is ", this.name);
11 },
12 // Shorter syntax
13 shout3() {
14 console.log("my name is ", this.name);
15 }
16};
17
18person.shout(); // "jason"
19person.shout2(); // "global"
20person.shout3(); // "jason"

As you see arrow functions always use their parent’s scope.

More articles