-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
In JavaScript, the this keyword is a fundamental concept that refers to the context in which a function or object is executed. Its value depends on how and where a function is called. Understanding this is crucial for building dynamic web applications, as it allows developers to access object properties, invoke methods, and maintain proper context in functions and event handlers.
In this tutorial, you will learn about the JavaScript this keyword, how it behaves in different contexts, practical examples, common mistakes, best practices, and real-world applications.
this Keyword Is ImportantThe this keyword is important because it:
Provides access to the current execution context
Allows methods to reference the object they belong to
Supports dynamic function invocation in different contexts
Enables object-oriented programming patterns in JavaScript
Helps manage scope in event handlers and callback functions
Without a proper understanding of this, code may produce unexpected results, especially when dealing with nested functions, event handlers, or object methods.
this Works in Different ContextsThe value of this changes depending on how a function is called. The main contexts include:
Global Context
Function Context
Object Method Context
Constructor Functions
Arrow Functions
Event Handlers
In the global execution context (outside any function), this refers to the global object. In browsers, this is usually the window object. In strict mode, this is undefined.
console.log(this); // Window object in browser
In strict mode:
"use strict";
console.log(this); // undefined
In a regular function, this refers to the global object in non-strict mode. In strict mode, it is undefined.
function showThis() {
console.log(this);
}
showThis(); // Window (non-strict) or undefined (strict)
When a function is called as a method of an object, this refers to the object that owns the method.
const student = {
name: "Priya",
greet: function() {
console.log("Hello, " + this.name);
}
};
student.greet(); // Hello, Priya
Here, this refers to the student object.
Inside constructor functions, this refers to the newly created object.
function Person(name, age) {
this.name = name;
this.age = age;
}
const aarushi = new Person("Aarushi", 25);
console.log(aarushi.name); // Aarushi
Arrow functions do not have their own this. They inherit this from the surrounding lexical scope.
const teacher = {
name: "Saanvi",
greet: function() {
const arrowFunc = () => console.log("Hello, " + this.name);
arrowFunc();
}
};
teacher.greet(); // Hello, Saanvi
In HTML event handlers, this usually refers to the element that received the event.
<button id="btn">Click Me</button>
<script>
const button = document.getElementById("btn");
button.addEventListener("click", function() {
console.log(this.id); // btn
});
</script>
Using arrow functions here would change the context of this:
button.addEventListener("click", () => {
console.log(this.id); // undefined, because arrow functions inherit lexical this
});
const student = {
name: "Aarushi",
introduce: function() {
console.log("My name is " + this.name);
}
};
student.introduce(); // My name is Aarushi
function Course(title, duration) {
this.title = title;
this.duration = duration;
}
const jsCourse = new Course("JavaScript Basics", "30 days");
console.log(jsCourse.title); // JavaScript Basics
const student = {
name: "Priya",
greet: function() {
function inner() {
console.log(this.name);
}
inner();
}
};
student.greet(); // undefined (strict mode) or Window.name
const student = {
name: "Priya",
greet: function() {
const inner = () => console.log(this.name);
inner();
}
};
student.greet(); // Priya
thisconst btn = document.getElementById("btn");
btn.addEventListener("click", function() {
console.log(this.id); // btn
});
call, apply, and bindYou can explicitly set this using these methods.
function greet(city) {
console.log(`Hello, ${this.name} from ${city}`);
}
const student = { name: "Aarushi" };
greet.call(student, "Patna"); // Hello, Aarushi from Patna
greet.apply(student, ["Patna"]); // Hello, Aarushi from Patna
const boundGreet = greet.bind(student);
boundGreet("Patna"); // Hello, Aarushi from Patna
Using regular functions inside objects or callbacks without understanding context
Expecting arrow functions to have their own this
Confusing this in strict vs non-strict mode
Relying on this in event handlers without binding
Misusing constructor functions without new
Use arrow functions for nested functions when you want to inherit this
Always use new with constructor functions
Use call, apply, or bind to explicitly set this when needed
Avoid unnecessary reliance on global this
Understand this behavior in event handlers for consistent results
Accessing and modifying object properties dynamically
Maintaining context in asynchronous callbacks and promises
Event handling in DOM elements
Implementing classes and constructor functions
Binding methods for reusable utility functions
The JavaScript this keyword provides access to the current execution context. Its value varies depending on whether it is used in the global scope, inside a function, an object method, a constructor function, an arrow function, or an event handler. Understanding how this works, combined with call, apply, and bind, allows developers to write modular, maintainable, and predictable code. Following best practices helps avoid common pitfalls and ensures proper context in complex applications.
Log this in the global context and explain the output in a browser and Node.js environment.
Create a regular function and log this inside it. Compare the result in strict and non-strict mode.
Define an object with a method and log this inside the method. Explain what this points to.
Create a nested function inside a method and log this inside the nested function. Explain the behavior.
Rewrite the nested function from the previous question using an arrow function and observe how this changes.
Create a class with a method and log this inside the method. Instantiate the class and call the method.
Create a static method in a class and log this inside it. Explain what this points to.
Use call() and apply() to invoke a function with a specific this context. Compare the results.
Use bind() to create a new function with this permanently set to a given object. Call the function and log the output.
Create a DOM element and attach an event listener. Log this inside a regular function and then inside an arrow function. Explain the difference.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
