what is "this" in javascript ??
I have explained how "this" keyword behaves in javascript in different places.
Introduction
let's start with an understanding of this
of course, you will say he is Hitesh sir a popular YouTuber, teacher, and Entrepreneur who cares for students ππππ
But this is our normal day-to-day life example does this work like this in javascript A big question?????
let's understand how this works in javascript
What is "this"?
A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.
In JavaScript, the
this
keyword refers to an object.Which object depends on how this is being invoked (used or called).
- The this keyword refers to different objects depending on how it is used:
this is not a variable. It is a keyword. You cannot change the value of this.
let's understand the behavior of this
in different places. are you all excited to understand???
"this" Alone
- When used alone,
this
refers to the global object. - Because this is running in the global scope.
- In a browser window the global object is [object Window]:
let a=this;
console.log(a)
output
see it is referring to the global object
π³let's see what happens when we use the strict mode β οΈβ οΈ
"use strict";
let a=this;
console.log(a)
output
In strict mode, when used alone, this
also refers to the global object.
"this" in a Function (Default)ππ
In a function, the global object is the default binding for this.
In a browser window the global object is [object Window]:
function myFunction() {
console.log(this);
}
myFunction();
output
"this" in a Function (Strict) ππ
JavaScript strict mode does not allow default binding.
So, when used in a function, in strict mode, this is undefined.
"this" in a Method β½
- When used in an object method, this refers to the object.
Let's see how???π€π€π€π€
const profile = {
name: "prajwal",
age: 23,
method: function () {
console.log(this);
},
};
profile.method();
see the above example we create one object and in that object, we write one method in which we did console log for this
Here is the output
yes, it is referring to an objectπ€©π€©π€©π€©π€©
"this" in Event Handlers
In HTML event handlers, this refers to the HTML element that received the event:
<button onclick="this.style.display='none'">
Click to Remove Me!
</button>
//If you click on the button, the button gets removed means it is referring to an HTML element
Conclusion
I tried to explain in this article how this keyword works in javascript in different places. I hope that this article is useful to you, to help understand the topic better. If you have any questions, you can leave them in the comments section below.
Happy Coding.
ByBy