DEV Community

Joe Avila
Joe Avila

Posted on

What is this?

In javascript, you have access to this keyword at any time. Unless there are certain conditions met this will always refer to the global object Window. console.log(this) in your console to see the Window object.

Methods and thisBinding

One use case where this will change is in an object method. A method is a function stored as an object property, like displayObject below. If you run the code block in your console you'll first see the window object like before and then the updated value for this, our new object.

console.log(this)

const myObject = {
   type: 'Object',
   purpose: 'Give an example.',
   displayObject: function() {
       console.log(this)
   }
}

myObject.displayObject()
Enter fullscreen mode Exit fullscreen mode

If you understand the process for an execution context than this will be easy to understand. Every time a new execution context is created thisBinding is evaluated. If it's called on a method, this becomes the object that owns the method. Otherwise, it remains the Window object. There are other circumstances where this can change, and if you're interested in learning more other users go into a much deeper dive in the topic than I do in this article.

Top comments (0)