14. this keyword - Javascript
this
is a special keyword in JavaScript that refers to the object that is executing the current function. Its value depends on how the function is called.
this
Used Alone (Global Context)//In Node.js console.log(this); // {} (return empty object) //In Browser console.log(this); // Window object (return window object)
2.this
in a Regular Function
//In Node js
function showThis(){
console.log(this); // global object (In Strict Mode it is undefined)
}
showThis()
//In Browser
function showThis(){
console.log(this); // window object (In Strict Mode it is undefined)
}
showThis()
this
inside object// In Node js let obj ={ name:"Ayy", age:"21", f: function(){ console.log(this) } } obj.f(); //{ name: 'Ayy', age: '21', f: [Function: f] } (return object itself) //In Borwser -> return object itself
this
in an Event HandlerIn an event listener,
this
refers to the element that triggered the event.<button id="btn">Click Me</button> <script> document.getElementById("btn").addEventListener("click", function() { console.log(this); // Output: <button id="btn">Click Me</button> }); </script>
this
in an Arrow FunctionArrow functions do not have their own
this
.They inherit
this
from their surrounding lexical scopeconst obj = { name: "Arrow Function", getName: () => { console.log(this.name); } }; obj.getName(); // Output: undefined
Inside a method
const obj = {
name: "JavaScript",
getName: function () { // arrow inside function
const arrowFn = () => console.log(this.name);
arrowFn();
}
};
obj.getName(); // Output: "JavaScript"
Interview questions
What will be the output of this function inside an object?
const obj = { name: "JavaScript", getName: function () { console.log(this.name); } }; obj.getName();
Output:
"JavaScript"
this
refers toobj
becausegetName()
is called as an object method.
How do you fix
this
inside a nested function?Arrow functions (they inherit
this
from their parent scope).bind(this)
to manually setthis
.const obj = { name: "JavaScript", getName: function () { const innerFunction = () => console.log(this.name); innerFunction(); } }; obj.getName(); // Output: "JavaScript"