Home Web Front-end JS Tutorial The Final Steps to Mastering JavaScript's 'this' Keyword

The Final Steps to Mastering JavaScript's 'this' Keyword

Feb 19, 2025 pm 01:17 PM

The Final Steps to Mastering JavaScript's

The basic usage of JavaScript this keyword has been explained in the previous article. thisThe key to pointing is the runtime context. However, when the context changes beyond expectations, the problem arises. This article will focus on this situation and how to solve it.

Core points

  • The this keyword in JavaScript points to the current execution context, and understanding it is essential for manipulating and interacting objects, especially when object-oriented programming or using frameworks and libraries that rely heavily on this.
  • Common problems with
  • this Keywords include use in extracted methods, callback functions, and closures. These problems can be solved by explicitly binding the bind() keyword to the correct object using the this method.
  • ECMAScript 6 introduces an arrow function that gets the this value from its direct enclosing scope. The lexical binding of the arrow function cannot be overwritten, making it a more elegant solution to maintain the correct context. this The value of
  • depends on how the function is called. In the method, this points to the object to which it belongs; in a normal function, this points to the global object; if the function is called with the this keyword (as a constructor), new points to the newly created object; In the event handler, this points to the element that receives the event; finally, this can be explicitly set using call(), apply() or bind(). this

Solve FAQs

This section will explore some of the most common problems that arise when using the

keywords and learn how to solve them. this

1. Use this in the extraction method One of the most common mistakes of is trying to assign the object's method to a variable and expect

to still point to the original object. As shown in the following example, this doesn't work.

this

Even if
var car = {
  brand: "Nissan",
  getBrand: function() {
    console.log(this.brand);
  }
};

var getCarBrand = car.getBrand;

getCarBrand(); // 输出:undefined
Copy after login
Copy after login
Copy after login
seems to be a reference to

, it is actually just another reference to getCarBrand itself. We already know that the call location determines the context, and here the call location is car.getBrand(), which is a simple function call. To prove that getBrand() points to a function without a base (a function not bound to any specific object), just add getCarBrand() at the bottom of the code and you will see the following output: getCarBrand

var car = {
  brand: "Nissan",
  getBrand: function() {
    console.log(this.brand);
  }
};

var getCarBrand = car.getBrand;

getCarBrand(); // 输出:undefined
Copy after login
Copy after login
Copy after login

getCarBrand contains only one normal function, which is no longer a member method of the car object. So in this case, this.brand is actually converted to window.brand, of course it is undefined. If we extract the method from the object, it becomes a normal function again. Its connection to the object is cut off and no longer works as expected. In other words, the extracted function is not bound to the object it takes from. So how do we remedy it? If we want to keep a reference to the original object, we need to explicitly bind the getBrand() function to the getCarBrand object when assigning the getBrand() function to the car variable. We can use the bind() method to achieve it.

function(){
  console.log(this.brand);
}
Copy after login
Copy after login

Now we get the correct output because we successfully redefined the context to what we want it to look like.

2. Use this in the callback function

The next problem occurs when we pass a method (using

as an argument) as the callback function. For example: this

var getCarBrand = car.getBrand.bind(car);
getCarBrand(); // 输出:Nissan
Copy after login
Even if we use

, we actually only get the function car.getBrand attached to the button object. Passing parameters to a function is an implicit assignment, so what happens here is almost the same as in the previous example. The difference is that now getBrand() is not an explicit assignment, but an implicit assignment. The result is almost the same - what we get is a normal function bound to a button object. In other words, when we execute a method on an object, the object is different from the object that originally defined the method, and the car.getBrand keyword no longer points to the original object, but to the object that called the method. Refer to our example: We execute this on the el (button element), instead of the car.getBrand object it originally defined. Therefore, car no longer points to this, but to car. If we want to keep the reference to the original object unchanged, we also need to explicitly bind the el function to the bind() object using the getBrand() method. car

var car = {
  brand: "Nissan",
  getBrand: function() {
    console.log(this.brand);
  }
};

var el = document.getElementById("btn");
el.addEventListener("click", car.getBrand);
Copy after login
Now everything works as expected.

3. Use in closure this Another situation where the context of

can go wrong is that we use this within the closure. Consider the following example: this

el.addEventListener("click", car.getBrand.bind(car));
Copy after login
The output here is

because the closure function (internal function) cannot access the undefined variable of the external function. The end result is that this is equal to this.brand, because window.brand in the inner function is bound to the global object. To solve this problem, we need to bind the this to the this function. getBrand()

var car = {
  brand: "Nissan",
  getBrand: function() {
    var closure = function() {
      console.log(this.brand);
    };
    return closure();
  }
};

car.getBrand(); // 输出:undefined
Copy after login
This binding is equivalent to

. Another popular way to fix closures is to assign the car.getBrand.bind(car) value to another variable, thus preventing unexpected changes. this

var car = {
  brand: "Nissan",
  getBrand: function() {
    console.log(this.brand);
  }
};

var getCarBrand = car.getBrand;

getCarBrand(); // 输出:undefined
Copy after login
Copy after login
Copy after login

Here, the value of this can be assigned to _this, that, self, me, my, context,

,

, , ,

,

, the pseudonym of the object, or any other name that suits you. The key is to keep references to the original object. this thisfunction Rescue of ECMAScript 6=>this newIn the previous example, we see the so-called "lexical method var self = this;" - when we assign the

value to another variable. In ECMAScript 6, we can use similar but more elegant techniques to achieve this with new arrow functions. The arrow function is not created by the
function(){
  console.log(this.brand);
}
Copy after login
Copy after login
keyword, but by the so-called "fat arrow" operator (

). Unlike normal functions, arrow functions obtain values ​​from their directly enclosed scope. The lexical binding of arrow functions cannot be overwritten, even with the this operator. Now let's see how to replace the statement using the arrow function.

this

What to remember about
  • thisWe see the
      keyword, like any other mechanism, follow some simple rules, and if we understand them well, we can use the mechanism with more confidence. So, let's take a quick look at what we've learned (from this article and the previous article):
    • In the following cases,
    • points to the global object:
    • In the outermost context, outside any function block.
  • In a function that is not an object method.
  • thisIn functions that are not object constructors.
  • call() apply() When the function is called as the property of the parent object, bind() points to the parent object. this nullWhen a function is called using this or
  • or
  • , new points to the first parameter passed to these methods. If the first parameter is this or is not an object, then
  • points to the global object.
  • thisWhen calling a function using the
  • operator,
points to the newly created object.

this When using arrow functions (introduced in ECMAScript 6),

depends on the lexical scope and points to the parent object.

Learn these simple and clear rules, we can easily predict what

will point to, and if it is not what we want, we know what methods can be used to fix it.

thisthisSummary

JavaScript's this keyword is a difficult concept to master, but you can master it with just practice more. I hope this article and my previous article will serve as a basis for your understanding and will be a valuable reference the next time you give you a headache.

JavaScript FAQs for keywords (FAQs)

(The FAQs part is omitted here because it is too long and is highly duplicated with the previous content. The FAQs part has been explained in detail earlier.)

The above is the detailed content of The Final Steps to Mastering JavaScript's '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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles