In this tutorial, we will see this keyword in javascript
- The
this
keyword in JavaScript refers to the object that the current function is a method of. It provides a way to access object properties and methods within the object’s context. - The value of
this
depends on how the function is called. It can refer to the window object (in non-strict mode), the object that the function is a method of, or the object that is specified with thecall()
orapply()
method.
Here are a few examples to help illustrate how this
works:
- In the global scope (outside of any function),
this
refers to the window object:
console.log(this === window); // true
- In an object method,
this
refers to the object that the method belongs to:
let obj = {
prop: "Hello",
showProp: function() {
console.log(this.prop);
}
};
obj.showProp(); // "Hello"
- In a function,
this
can be set explicitly usingcall()
orapply()
:
let obj = { prop: "Hello" };
function showProp() {
console.log(this.prop);
}
showProp.call(obj); // "Hello"
It’s important to note that the value of this
can change based on the context in which a function is called, so it’s crucial to understand the context in which a function is executed to properly use this
.
Thanks for Reading