- Courses
- đ»Programming Languages
- đJavaScript
- Objects and Classes
- this Keyword
On this page
The this Keyword and Execution Context
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
The this keyword is one of the most powerful yet frequently misunderstood features of JavaScript. Unlike many other programming languages where this always refers to the instance of a class, in JavaScript, the value of this is dynamic. It is determined entirely by the execution contextâspecifically, how a function is invoked, rather than where it is defined.
Understanding Execution Contextâ
In JavaScript, every time code runs, it does so within an execution context. You can think of the this keyword as a reference to the "owner" of the function currently being executed. To identify what this refers to, you must look at the call site (the location in the code where the function is called).
Global Contextâ
When code is executed in the outermost level of a script, outside of any function, this refers to the global object.
- In a web browser, the global object is
window. - In a strict mode environment (
"use strict";),thisat the global level remains the global object, but inside a standalone function, it will beundefinedto prevent accidental global modifications.
console.log(this); // In a browser, this outputs the Window object
function checkThis() {
return this;
}
console.log(checkThis()); // In non-strict mode: Window. In strict mode: undefined.
Object Method Bindingâ
When a function is called as a method of an object, this is bound to the object that "owns" the method. This is often referred to as Implicit Binding. This allow methods to access and manipulate other properties within the same object.
const userProfile = {
username: "ProfessorJS",
greet: function () {
console.log("Hello, my name is " + this.username);
},
};
userProfile.greet(); // Output: Hello, my name is ProfessorJS
In this scenario, this points to userProfile because the function was called using the dot notation (userProfile.greet()).
The "Lost" Context Problemâ
A common source of confusion occurs when a method is extracted from its object and assigned to a variable. When you call that variable as a standalone function, the connection to the original object is severed, and this reverts to the global object (or undefined).
const detachedGreet = userProfile.greet;
detachedGreet(); // Output: Hello, my name is undefined
Because detachedGreet() is called without a leading object reference, the execution context changes, and this no longer points to userProfile.
Constructor Contextâ
When a function is used as a constructor with the new keyword, a brand-new object is created. In this context, this is bound to the newly created instance.
function Smartphone(brand) {
this.brand = brand;
}
const myPhone = new Smartphone("Apple");
console.log(myPhone.brand); // Output: Apple
The new keyword explicitly redirects the this binding to the empty object it just generated.
Explicit Binding: call, apply, and bindâ
JavaScript provides three methods that allow developers to manually set the value of this, regardless of how the function is called. This is known as Explicit Binding.
- call(): Invokes the function immediately with a specified
thisvalue and arguments passed individually. - apply(): Similar to
call(), but arguments are passed as an array. - bind(): Does not invoke the function immediately. Instead, it returns a new version of the function where
thisis permanently locked to a specific object.
function describe(price, currency) {
console.log(this.item + " costs " + price + currency);
}
const product = { item: "Laptop" };
describe.call(product, 1200, "USD"); // Immediate execution
const boundDescribe = describe.bind(product); // Returns a new function
boundDescribe(1200, "USD"); // Execution later
The Exception: Arrow Functionsâ
It is important to note that Arrow Functions behave differently. They do not have their own this binding. Instead, they inherit this from the surrounding lexical scope (the code that contains the arrow function). This makes them particularly useful for callbacks and timers where you want to maintain the context of the parent object.
Technical Precision Checklistâ
To accurately predict the value of this, apply these rules in order of priority:
- New Binding: Is the function called with
new? If so,thisis the new object. - Explicit Binding: Is the function called with
call,apply, orbind? If so,thisis the specified object. - Implicit Binding: Is the function called as a method (e.g.,
obj.method())? If so,thisis that object. - Default Binding: Is it a standalone function call? If so,
thisis the global object (orundefinedin strict mode).
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Objects
Next
Prototypes & Inheritance
- Understanding Execution Context
- Global Context
- Object Method Binding
- The "Lost" Context Problem
- Constructor Context
- Explicit Binding: call, apply, and bind
- The Exception: Arrow Functions
- Technical Precision Checklist
