What is "this" in Javascript?

What is "this" in Javascript?

ยท

2 min read

Introduction

This this confuses many developers as it behaves differently in different environments, Let's get straight to the point.

this is an object that refers to the current execution function, it means that this can have different values according to their context, let's take an example.

Here we have simple logging this,

console.log(this)

When the above code will compile it will have result something like this

image.png

It means that its current context/object is the Windowobject where it is executed.

this in a function

this has the same context in the global function because the function is called in a global context, so that's why it returns the same Window object.

function func() {
    console.log(this)    
}

func();

image.png

this in constructor function

In constructor function this refers to its current context like in code below if you see a log you can see an empty Object.

Why this happens?

Because whenever you use a new keyword with class or constructor functions a new object is created and in object thisalways refer to its current context.

function Car() {
    console.log(this)
}

const _car = new Car()  // {}

image.png

Let's take another example

Now in the constructor function, one parameter is passing through it and we inject that parameter into this object and after logging it you can see thetitle in this object.

function Car(title) {
    this.title = title;
    console.log(this)
}

const _car = new Car('Audi')

image.png

this in methods

As we already discussed this in methods always refers to its current context. In car object we have method drive and after logging this you can see the whole object in this.

const car = {
  name: 'Audi',

  drive: function(){
    console.log(this)
  }      
}

car.drive()

image.png

Conclusion

this is not that much confusing if we leave the theoretical part and focus on code and its behaviour, you can play with this as much as you want ๐Ÿ˜ƒ and let me know in the comments if you have something interesting with this.

Don't forget to follow me on hashnode and on other plaforms (Bio Link)