DEV Community

Cover image for What is .this?
Bryanjazo
Bryanjazo

Posted on

What is .this?

Intro

I was quite interested in the keyword .this in javascript, through the weekend doing some research helped me understand why

.this

is more than what it seems.

What is .this

.this

Is a keyword that references another value most likely an object that represents the current

current execution context

You might ask what is current execution context. Well, the current execution context means that .this inside a function references the object function at a given time. If you'd like to give it a try, go into your DEV tools and try out

console.log(this)

Now you should be able to see something like this,

Window {window: Window, self: Window, document: document, name: "", location: Location, …}.

What .this means here is the global object of the browser.

.this in functions

Now things get super interesting when we create a function and repeat what we did in the browser with console.log but now inside the function, let's create a function to demonstrate.

function testingThis(){
 console.log(this)
}
testingThis();
Enter fullscreen mode Exit fullscreen mode

Now you see we get the same thing, that's because our global context is still executed in the function. Now let's take the same function and use it as a property on an object.

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

const chromeBoi = {
 status: "cool",
    testingThis,
}

chromeBoi.testingThis();
Enter fullscreen mode Exit fullscreen mode

Now this will give you the object of chrome boy In the calling of it.

This and classes

Now the biggest question I had after going through all the documentation is how does .this work with classes? how does javascript know what this is and how to assign it. Now with classes, it a different story the way to understand how .this works with classes is to understand that every time we instantiate a new instance of the class, let's name our class ChromeRules when we instantiate it as so,

c = new ChromeRules(someObject)

Enter fullscreen mode Exit fullscreen mode

What we're doing here is we're creating a new object which in general will let us understand what this would be which is the object of the new instance of ChromeRules so if we had a function inside the class ChromeRules .this in this sense will be the object being passed in and will be called on the function being called on for example,

c.listName();

Enter fullscreen mode Exit fullscreen mode

Conclusion

this search was a really good refresher going into a different language react, And knowing this is a big advantage.

Top comments (0)