this Keyword in JavaScript
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:
Global context:
this
refers to the global object (window
in browsers,global
in Node.js).Object methods:
this
refers to the object that calls the method.Constructor functions:
this
refers to the instance of the object created by the constructor.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 withvar
are properties of thewindow
object.In Node.js, the global object is
global
, notwindow
.
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 thewindow
object, which is why you can also call it usingwindow.sayHello()
.
Similarly, global variables declared with var
behave the same way:
Important Notes:
- Global variables declared with
let
orconst
do not become properties of thewindow
object.
Subscribe to my newsletter
Read articles from dheeraj koranga directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by