this keyword in JavaScript
The "this" Keyword in JavaScript - Complete Guide
Hey everyone! Welcome back to Namaste JavaScript. Today we are going to study one of the most confusing topics in JavaScript - the "this" keyword.
The problem with "this" keyword is that it behaves very differently in different circumstances:
- Inside global space - different behavior
- Inside a function - different behavior
- Inside an arrow function - different behavior
- Inside an object's method - different behavior
- Inside DOM elements - different behavior
Let's understand each one by one!
1. "this" in Global Space
Global space means anything written outside of any function.
console.log(this);
OUTPUT:
Window {window: Window, self: Window, ...}
Key Point: In global space, "this" refers to the global object.
- In browsers - global object is window
- In Node.js - global object is global
- Different JavaScript runtimes have different global objects
2. "this" Inside a Function
This is where it gets tricky! The value depends on strict mode vs non-strict mode.
Non-strict mode:
function x() {
console.log(this);
}
x();
OUTPUT:
Window {window: Window, self: Window, ...}
Strict mode:
"use strict";
function x() {
console.log(this);
}
x();
OUTPUT: undefined
Why this difference? Because of something called "this substitution"!
What is "this" Substitution?
Note this down - very important!
this substitution: If the value of "this" keyword is undefined or null, it will be replaced with the global object (only in non-strict mode).
// In strict mode
"use strict";
function x() {
console.log(this); // undefined (actual value)
}
x();
// In non-strict mode
function x() {
console.log(this); // window (because of this substitution)
}
x();
OUTPUT:
// Strict mode: undefined
// Non-strict mode: Window {...}
3. "this" Depends on How the Function is Called
Very important! The value of "this" depends on how the function is called.
"use strict";
function x() {
console.log(this);
}
x(); // Called without reference
window.x(); // Called with window reference
OUTPUT:
undefined // x() - no reference, so undefined
Window {...} // window.x() - reference is window
Rule: If called without any object reference = undefined. If called with object reference = that object becomes "this".
4. "this" Inside an Object's Method
First, what's the difference between function and method?
- Function: Standalone function
- Method: Function inside an object
const student = {
name: "Akshay",
printName: function() {
console.log(this);
}
};
student.printName();
OUTPUT:
{ name: "Akshay", printName: f }
Inside a method, "this" refers to the object that the method belongs to!
const student = {
name: "Akshay",
printName: function() {
console.log(this.name);
}
};
student.printName();
OUTPUT: Akshay
5. call, apply, bind - Sharing Methods
What if you want to use a method from one object with another object?
const student = {
name: "Akshay",
printName: function() {
console.log(this.name);
}
};
const student2 = {
name: "Deepika"
};
student.printName(); // Akshay
OUTPUT: Akshay
Now I want to use printName for student2. Can I do student2.printName()? NO! It doesn't exist on student2.
Solution: Use call() to override the value of "this"!
student.printName.call(student2);
OUTPUT: Deepika
How it works:
student.printName- refers to the function.call(student2)- calls it with "this" = student2- Inside the function, "this" now points to student2!
Important: Learn call, apply, and bind - very important interview topics!
6. "this" Inside Arrow Functions
This is the trickiest part! Remember these words: Enclosing Lexical Context.
Key Point: Arrow functions do NOT have their own "this" binding. They take "this" from their enclosing lexical context.
Example 1: Arrow function in global scope
const obj = {
a: 10,
x: () => {
console.log(this);
}
};
obj.x();
OUTPUT:
Window {...}
Why window? The arrow function doesn't have its own "this". It looks at where it's lexically enclosed - which is the global scope. So "this" = window.
Example 2: Arrow function inside a regular function
const obj2 = {
a: 20,
x: function() {
const y = () => {
console.log(this);
};
y();
}
};
obj2.x();
OUTPUT:
{ a: 20, x: f }
Why obj2? The arrow function y() looks at its enclosing lexical context, which is function x(). Inside x(), "this" = obj2. So the arrow function also gets obj2!
How to think about it: Pretend the arrow function doesn't exist. Where would the console.log be? That's the enclosing lexical context!
// Think of it like this:
const obj2 = {
a: 20,
x: function() {
// Arrow function's "this" behaves as if written here
console.log(this); // this = obj2
}
};
7. "this" in DOM Elements
When using "this" in DOM event handlers:
<button onclick="alert(this)">Click Me</button>
OUTPUT: (on click) [object HTMLButtonElement]
"this" refers to the HTML element that received the event!
<button onclick="alert(this.tagName)">Click Me</button>
OUTPUT: (on click) BUTTON
Quick Recap - Interview Cheat Sheet
| Context | Value of "this" |
|---|---|
| Global space | Global object (window in browser) |
| Function (strict mode) | undefined |
| Function (non-strict mode) | Global object (this substitution) |
| Object's method | The object itself |
| Arrow function | Enclosing lexical context |
| DOM element | The HTML element |
| call/apply/bind | Whatever you pass as first argument |
Interview Tips - How to Explain
Q: What is "this" keyword in JavaScript?
"The 'this' keyword refers to the object that is executing the current function. Its value depends on how and where the function is called. In global space, it's the global object. Inside a method, it's the object. In arrow functions, it takes the value from enclosing lexical context. The value also differs in strict vs non-strict mode."
Q: What is "this substitution"?
"In non-strict mode, if the value of 'this' is undefined or null, JavaScript automatically replaces it with the global object. This is called 'this substitution'."
Q: How does "this" work in arrow functions?
"Arrow functions don't have their own 'this' binding. They inherit 'this' from their enclosing lexical context - meaning wherever they are written in the code, they take 'this' from that surrounding scope."
Key Points to Remember
- Global space: "this" = global object
- Function (strict): "this" = undefined
- Function (non-strict): "this" = global object (this substitution)
- Method: "this" = the object containing the method
- Arrow function: "this" = enclosing lexical context
- DOM: "this" = the HTML element
- call/apply/bind: Can override "this" value
- "this" value depends on HOW the function is called
Keep coding, keep learning!
Post a Comment