亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
2. Four Main Rules for this
? Rule 1: Implicit Binding (Most Common)
? Rule 2: Explicit Binding (call, apply, bind)
? Rule 3: New Binding (new keyword)
? Rule 4: Default Binding (Fallback)
3. Arrow Functions Change the Game
4. Common Pitfalls & Fixes
? Lost context in callbacks
Home Web Front-end Front-end Q&A Demystifying the JavaScript `this` Keyword

Demystifying the JavaScript `this` Keyword

Jul 28, 2025 am 03:33 AM
this

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.

Demystifying the JavaScript `this` Keyword

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.

Demystifying the JavaScript `this` Keyword

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.

Demystifying the JavaScript `this` Keyword
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.

Demystifying the JavaScript `this` Keyword

? 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 with this 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:

  1. Creates a new empty object.
  2. Sets this inside the function to that object.
  3. 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:

  1. Is new used? → this = new instance.
  2. Is call, apply, or bind used? → this = specified object.
  3. Is the function called on an object (e.g., obj.func())? → this = that object.
  4. Else → this = global (non-strict) or undefined (strict).
  5. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Let's talk about why Vue2 can access properties in various options through this Let's talk about why Vue2 can access properties in various options through this Dec 08, 2022 pm 08:22 PM

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!

An article that understands this point and catches up with 70% of front-end people An article that understands this point and catches up with 70% of front-end people Sep 06, 2022 pm 05:03 PM

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.

Clever way to use this keyword in jQuery Clever way to use this keyword in jQuery Feb 25, 2024 pm 04:09 PM

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? Brief analysis of three methods How does JavaScript change this pointer? Brief analysis of three methods Sep 19, 2022 am 09:57 AM

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? An in-depth analysis of this in JavaScript What is this? An in-depth analysis of this in JavaScript Aug 04, 2022 pm 05:02 PM

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!

Let me explain in detail the four binding rules of this Let me explain in detail the four binding rules of this Nov 01, 2022 pm 05:49 PM

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.

Detailed explanation of this in JavaScript arrow function Detailed explanation of this in JavaScript arrow function Jan 25, 2024 pm 01:41 PM

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.

How to use this method in Java How to use this method in Java Apr 18, 2023 pm 01:58 PM

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

See all articles