this Keyword in JavaScript

dheeraj korangadheeraj koranga
2 min read

The this keyword in JavaScript refers to the object that is currently executing the function. The value of this depends on how the function is called and can refer to different objects in different contexts.

Behavior of this in Different Contexts:

  1. Global context: this refers to the global object (window in browsers, global in Node.js).

  2. Object methods: this refers to the object that calls the method.

  3. Constructor functions: this refers to the instance of the object created by the constructor.

  4. Arrow functions: Arrow functions do not have their own this, they inherit it from the surrounding lexical context (where they are defined).

Global Context :

  • “this” keyword in global context refers to the window object

Object Methods :

  • “this” keyword refers to the “name” variable of the student object

What is the window Object?

The window object is the global object in a web browser that represents the browser's window or tab. It is automatically created by the browser and provides various properties and methods to interact with the browser window, such as controlling the window's size, opening new windows, or accessing the DOM.

  • In browsers, the window object is the global object, and all global variables or functions declared with var are properties of the window object.

  • In Node.js, the global object is global, not window.

Why Methods in Global Scope are Considered as window Object?

When you declare a function or a variable in the global scope (outside any function or object), it automatically becomes a property or method of the window object in a browser. This is because the global execution context is bound to the window object by default.

  • In this example, the function sayHello is declared globally, so it becomes a method of the window object, which is why you can also call it using window.sayHello().

Similarly, global variables declared with var behave the same way:

Important Notes:

  • Global variables declared with let or const do not become properties of the window object.

0
Subscribe to my newsletter

Read articles from dheeraj koranga directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

dheeraj koranga
dheeraj koranga