Understanding the this Keyword in JavaScript

The first thing that defines JavaScript is how it uses this.
this doesn't exist in other languages at the same level or in the same way it exists in JS." JavaScript makes itself unique (and tricky) by this .
When we check existence for this at global level running console.log(this) in node environment return empty {} (object) while at the same global level in browser will get window object.
Its use depends on the context.
when we check the position of this in browser
console.log(this)
We will received the window object
Run in the node environment
console.log("this ===>", this)
We will received the this ===> {}
when we run the below function in node node script.js
function ranveerOnGlobalStage() {
return typeof this;
}
console.log("ranveerOnGlobalStage ==>",ranveerOnGlobalStage());
we will get ranveerOnGlobalStage ==> undefined
because Node.js wraps every file inside a function internally. and global is Node.js-specific
if function is not running in global environment or its in functional scope that time you will get typeof undefined instead of Object. means function is not running in the real global scope or node has enabled by default "use strict" mode
Now interesting you can make it global stage by using call method
console.log(ranveerOnGlobalStage.call(global));
Now you will return Global object of node
function ranveerOnGlobalStage() {
return typeof this;
}
console.log("ranveerOnGlobalStage ==>",ranveerOnGlobalStage.call(global));
we will get the ranveerOnGlobalStage ==> object
How global and globalThis works you can check my link below https://node-js.hashnode.dev/understanding-global-vs-globalthis-in-javascript-and-node-js
function ranveerWithNoScript() {
return this;
}
console.log(ranveerWithNoScript()); //=> return undefined
console.log(ranveerWithNoScript.call(global));
return <ref *1> Object [global] { global: [Circular *1], .....
what will out in below function ? guess where is this pointing ?
If we run the code below
const bollywoodFilm2 = {
name: "Dhurandhar",
lead: "Ranveer",
introduce() {
return `\({this.lead} performs in \){this.name}`;
},
};
// console.log(bollywoodFilm2.introduce());
we will get the Ranveer performs in Dhurandhar because here this context is available.
What can we expect this in below regular nested function ?
const filmSet2 = {
crew: "Spot boys",
prepareProps() {
console.log(`Outer this.crew: ${this.crew}`);
function arrangeChairs() {
console.log(`Inner this.crew: ${this.crew}`);
}
arrangeChairs();
},
};
filmSet2.prepareProps();
why we will get here undefined
What we can expect this in below function ? this is in arrow function
const filmDirector = {
name: "Sanjay Leela Bhansali",
cast: ["Ranveer", "Deepika", "Priyanka"],
announceCast() {
// return
this.cast
.forEach((actor) => {
console.log(`\({this.name} introduces \){actor}`);
});
},
};
filmDirector.announceCast()
What we observe that in arrow function has printed this, normaly arrow function doesnt support this on global envirement but here, Arrow functions don't have their own this binding. They inherit this from the surrounding (lexical) scope:
Sanjay Leela Bhansali introduces Ranveer Sanjay Leela Bhansali introduces Deepika Sanjay Leela Bhansali introduces Priyanka
If you want to know about arrow function you can checkout my link blog arrow function https://js-functions.hashnode.dev/
how can we expect the output in below function nested arrow function
const filmSet = {
crew: "Spot boys",
prepareProps() {
console.log(`Outer this.crew: ${this.crew}`);
const arrangeLights = () => {
console.log(`Arrow this.crew: ${this.crew}`);
};
arrangeLights();
},
};
filmSet.prepareProps();
Outer this.crew: Spot boys Arrow this.crew: Spot boys
beacuse of this context avialable we received the result They inherit this from the surrounding (lexical) scope:
What we can expect the result from the regular nested function
const filmSet4 = {
crew: "Spot boys",
prepareProps() {
console.log(`Outer this.crew: ${this.crew}`);
function arrangeChairs() {
console.log(`Inner this.crew: ${this.crew}`);
}
arrangeChairs();
},
};
filmSet4.prepareProps();
Here we are calling the nested function with this context and defined the standalone method, Its js behavior that here we lost the this context and get undefined arrangeChairs();
How can we fixed ?
const filmSet5 = {
crew: "Spot boys",
prepareProps() {
console.log(`Outer this.crew: ${this.crew}`);
function arrangeChairs() {
console.log(`Inner this.crew: ${this.crew}`);
}
arrangeChairs.bind(this);
},
};
filmSet5.prepareProps();
The same function behaves differently based on how it's called:
function greet() {
return console.log(`Hello, I'm ${this.name}`);
}
const person = { name: "Advait", greet };
console.log(person.greet()); // without this
console.log(greet.call(person1)); // without this
console.log(greet.apply(person1)); // without this
*
* This is why JavaScript is said to have dynamic this binding - the value of this is determined at call-time, not at definition-time!
*
Now check the regular function without nested
function greet() {
return console.log(`Hello, I'm ${this.name}`);}
const person1 = { name: "Advait", greet };
// Hello, I'm Advait
console.log(person1.greet());
console.log(greet.call(person1));
And check arrow function without nested on global state
const greet = () => {
console.log(`Hello, I'm Arrow function ${this.name}`);
};
const person2 = { name: "Alice", greet };
person2.greet();
//Hello, I'm Arrow function undefined
Not received the this context, inherit this from the surrounding (lexical) scope:
another classic JavaScript this binding pitfall
const actor = {
name: "Ranveer",
bow() {
return `${this.name} takes a bow`;
},
};
// console.log(actor.bow());
const detachedBow = actor.bow;
console.log(detachedBow()); // without this
Functions in JS are first-class citizens.
actor.bow is a reference to the function. not copying the object
When called as actor.bow(), the object before the dot sets this.
When assigned to a variable and called directly, there's no object before the dot, so this defaults to global/undefined.
// Solution
const boundBow = actor.bow.bind(actor);
Conclusion behavior of JS: Regular function has own this in global state, It depends purely on HOW the function is called.
but they doesn't exist this in nested function, until you set using .call method. he doesn't have variable access there. In detached method also dont has variable access there, this will not access
Arrow function doesn't has its own this on global state, he doesn't have variable access there but in nested function it capture outer scope this, he took the reference of variable
Regular function: this is dynamic (call-site based) create new memory Arrow function: : this is lexical (scope based)
Behind the scene
When JS runs code, it creates:
Lexical Environment (Scope / Variables Memory)
Execution Context (Includes this)
this is NOT part of normal variable scope. It lives in the Execution Context, not inside the lexical variable environment..





