Skip to content
Gallery
Javascript
Share
Explore
Javascript

this keyword

Mastering the "this" Keyword in JavaScript

Global Context:
Outside any function, this points to the global object (e.g., window in browsers, global in Node.js).
In strict mode, it may be undefined.
Function Context:
Regular Functions:
Default Binding: When a function is called without a specific context, this defaults to the global object (or undefined in strict mode).
Implicit Binding: When called as a method (e.g., obj.method()), this points to the object.
Explicit Binding: Use call(), apply(), or bind() to set this explicitly.
Arrow Functions:
They don’t have their own this—instead, they inherit it from the surrounding (lexical) scope.
Cannot change this using call(), apply(), or bind().
Constructor Functions:
When using the new keyword, this refers to the newly created instance.
Always use new with constructor functions to avoid unintended global binding.
Event Handlers:
In regular functions used as event handlers, this refers to the DOM element that triggered the event.
Avoid arrow functions here if you need the event target as this, because they inherit this from the outer scope.
For detailed explanation:
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.