Understanding 'this' in JavaScript: Global Context, Functions, and Arrow Functions Explained".
1.Global Scope:-
This Refers to the Global object in the Dom .The Global object for the Dom is 'Window'.
console.log(this)
in this case the output will be "Window"
2.Within Function:-
This will print undefined within Functions in Strict Mode.But In Non strict Mode this refers to the window object .
function print() {
"use strict";
console.log(this); // This will output 'undefined' in strict mode
}
print();
In this case when print is called the output will be undefined if it is not not in another object.
function print() {
console.log(this); // This might refer to the global object (window in a browser) in non-strict mode
}
print();
In this case when print is called the output will be window object if it is not in any another object.
3.Arrow Function:-
Inside Arrow function this focuses on the lexical Environment .In strict mode when an arrow function is uses as a method of an object this does not refer to the object itself Instead, since arrow functions donβt have their own this context, they inherit the this value from the surrounding lexical scope at the time of their creation.
"use strict";
const obj = {
x: () => {
console.log( this) }
};
obj.x();
In this case when the x is called this will print Window object.
Subscribe to my newsletter
Read articles from Pritam Mukherjee directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Pritam Mukherjee
Pritam Mukherjee
Hi, I'm Pritam! π Full-stack developer and open-source enthusiast π Expertise in: HTML, CSS, JavaScript React, Next.js, Tailwind CSS, Bootstrap React Native MongoDB, Node.js, and the MERN stack 1 year of freelancing experience Currently running my own freelancing agency