this is determined by how a function is called, not where it’s defined. 2. The four rules in order of precedence are: if new is used, this refers to the newly created instance; if call, apply, or bind is used, this is explicitly set to the provided object; if the function is called on an object (e.g., obj.func()), this refers to the object before the dot; otherwise, this defaults to the global object in non-strict mode or undefined in strict mode. 3. Arrow functions do not have their own this but inherit it from the enclosing lexical scope, making them useful for preserving context in closures and callbacks. 4. Common pitfalls, such as losing context in event handlers, can be fixed using bind() or arrow function wrappers to maintain the intended this value. Understanding these rules allows developers to predict this behavior reliably.
The JavaScript this
keyword confuses many developers — not because it’s inherently complex, but because its value changes depending on how a function is called. Once you understand the rules that govern this
, it stops being mysterious. Let’s break it down with clarity and practical examples.

1. this
Depends on Execution Context
In JavaScript, this
refers to the execution context of a function — that is, how the function is invoked, not where it’s defined.
Unlike variables declared with let
or const
, this
isn’t about scope — it’s about invocation context.

function sayHi() { console.log(this.name); }
Depending on how sayHi()
is called, this
could point to different objects.
2. Four Main Rules for this
There are four primary ways this
gets determined. They follow an order of precedence.

? Rule 1: Implicit Binding (Most Common)
When a function is called as a method of an object, this
refers to that object.
const user = { name: "Alice", greet() { console.log(`Hi, I'm ${this.name}`); } }; user.greet(); // "Hi, I'm Alice"
? this
= object before the dot (user
).
?? Caveat: If you extract the method, you lose the context:
const greet = user.greet; greet(); // "Hi, I'm undefined" — `this` is now global (or `undefined` in strict mode)
? Rule 2: Explicit Binding (call
, apply
, bind
)
You can manually set this
using .call()
, .apply()
, or .bind()
.
function introduce() { console.log(`I'm ${this.name}, ${this.age} years old.`); } const person = { name: "Bob", age: 30 }; introduce.call(person); // "I'm Bob, 30 years old." introduce.apply(person); // same
call(thisArg, arg1, arg2, ...)
apply(thisArg, [argsArray])
bind(thisArg)
returns a new function withthis
permanently set.
const boundIntro = introduce.bind(person); boundIntro(); // Always uses `person` as `this`
Useful for callbacks or event handlers where context might be lost.
? Rule 3: New Binding (new
keyword)
When a function is called with new
, this
refers to the newly created object.
function Person(name) { this.name = name; // `this` = newly created instance this.greet = function() { console.log(`Hello, I'm ${this.name}`); }; } const p = new Person("Charlie"); p.greet(); // "Hello, I'm Charlie"
Under the hood, new
does this:
- Creates a new empty object.
- Sets
this
inside the function to that object. - Returns the object (unless another object is explicitly returned).
? Rule 4: Default Binding (Fallback)
When none of the above apply, this
defaults to the global object — or undefined
in strict mode.
function showThis() { console.log(this); } showThis(); // In browser: `window` (non-strict), `undefined` (strict)
?? This is why relying on global this
is dangerous — especially in modules (which are strict by default).
3. Arrow Functions Change the Game
Arrow functions don’t have their own this
. Instead, they inherit this
from the enclosing lexical scope.
const user = { name: "Diana", regularFunc: function() { console.log(this.name); // "Diana" }, arrowFunc: () => { console.log(this.name); // undefined (inherits `this` from outside) } }; user.regularFunc(); // Works user.arrowFunc(); // Doesn't work as expected
Why? At the time the arrow function was defined, this
in the outer scope was likely window
(or undefined
).
? Use arrow functions when you want to preserve the outer
this
— common in closures and event handlers.
function Timer() { this.seconds = 0; setInterval(() => { this.seconds ; // ? `this` refers to the Timer instance }, 1000); }
If you used a regular function here, this
would point to the global object or be undefined
.
4. Common Pitfalls & Fixes
? Lost context in callbacks
const button = document.querySelector('button'); const widget = { clicked: false, onClick() { this.clicked = true; console.log(this.clicked); } }; button.addEventListener('click', widget.onClick); // `this` is the button (DOM element), not `widget`
? Fix with .bind()
:
button.addEventListener('click', widget.onClick.bind(widget));
? Or use an arrow function wrapper:
button.addEventListener('click', () => widget.onClick());
Summary: How to Determine this
Ask in this order:
- Is
new
used? →this
= new instance. - Is
call
,apply
, orbind
used? →this
= specified object. - Is the function called on an object (e.g.,
obj.func()
)? →this
= that object. - Else →
this
= global (non-strict) orundefined
(strict). - For arrow functions: look to the enclosing scope.
Understanding this
isn’t about memorizing edge cases — it’s about knowing these rules and applying them step by step. Once you internalize the four binding rules and remember how arrow functions behave, this
becomes predictable.
Basically, just follow the call site.
The above is the detailed content of Demystifying the JavaScript `this` Keyword. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article will help you interpret the vue source code and introduce why you can use this to access properties in various options in Vue2. I hope it will be helpful to everyone!

A colleague got stuck due to a bug pointed by this. Vue2’s this pointing problem caused an arrow function to be used, resulting in the inability to get the corresponding props. He didn't know it when I introduced it to him, and then I deliberately looked at the front-end communication group. So far, at least 70% of front-end programmers still don't understand it. Today I will share with you this link. If everything is wrong If you haven’t learned it yet, please give me a big mouth.

Flexible use of this keyword in jQuery In jQuery, the this keyword is a very important and flexible concept. It is used to refer to the DOM element currently being manipulated. By rationally using this keyword, we can easily operate elements on the page and achieve various interactive effects and functions. This article will combine specific code examples to introduce the flexible use of this keyword in jQuery. Simple this example First, let's look at a simple this example. Suppose we have a

How does JavaScript change this pointer? The following article will introduce to you three methods of changing this pointer in JS. I hope it will be helpful to you!

What is this? The following article will introduce you to this in JavaScript, and talk about the differences between this in different calling methods of functions. I hope it will be helpful to you!

The this keyword is one of the most complex mechanisms in JavaScript. It is a very special keyword that is automatically defined in the scope of all functions. But even very experienced JavaScript developers have a hard time telling what exactly it points to.

The arrow function in JavaScript is a relatively new syntax. It does not have its own this keyword. On the contrary, the this of the arrow function points to the scope object containing it. The impacts are: 1. This in the arrow function is static; 2. Arrow Functions cannot be used as constructors; 3. Arrow functions cannot be used as methods.

1. this keyword 1. Type of this: Which object is called is the reference type of that object 2. Usage summary 1. this.data;//Access attribute 2. this.func();//Access method 3.this( );//Call other constructors in this class 3. Explanation of usage 1.this.data is used in member methods. Let us see what will happen if this is not added classMyDate{publicintyear;publicintmonth;publicintday; publicvoidsetDate(intyear,intmonth,intday){ye
