Understanding 'this' in JavaScript: Global Context, Functions, and Arrow Functions Explained".

Photo by Andrew Neel on Unsplash

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.