Does `this` always refer to an object?


#1

Question

Does this always refer to an object?

Answer

Yes, in JavaScript this will always refer to an object, the important part is to always know which object that is. For example:

const goat = {
  dietType: 'herbivore',
  makeSound() {
    console.log('baaa');
  },
  diet() {
    console.log(this.dietType);
  }
};

Since the method diet is a regular function, the meaning of the this keyword inside it relates to the method’s object since the context where regular functions exist dictates what they can use. Yet, if you were to do this in an empty js file:

console.log(this)

When you run the file (let’s say using node: node nameOfFile.js) on your terminal, this will be set to the global object which in that case will be the execution system (node) and you will probably see something like this on your terminal:
[obj]

If your JavaScript file was linked to an HTML page, then once it runs in the browser, the window object will become the global object, and calling the previous console.log would print the window object. The same way, setting functions as event listeners for HTML elements will make that any reference to this inside of the event listener function will relate to the HTML element it has been appended to.

------------ window --------------------------------------
|                                          / \           |
|                                           |            |
|                                          this          |
|   ----------------                        |            |
|   | HTML element | <-- this     ---------------------  |
|   ----------------      |      | functionInGlobal() |  |
|               |         |       ---------------------  |
|          --------------------                          |
|          | onclick property |                          |
|          --------------------                          |
|                                                        |
----------------------------------------------------------

That said, before using the keyword this always make sure you know which object it will refer to.


Arrow Functions and this