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.
thisUsed 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()
thisinside 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 itselfthisin an Event HandlerIn an event listener,
thisrefers 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>thisin an Arrow FunctionArrow functions do not have their own
this.They inherit
thisfrom 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"thisrefers toobjbecausegetName()is called as an object method.
How do you fix
thisinside a nested function?Arrow functions (they inherit
thisfrom 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"