search
HomeWeb Front-endJS TutorialThe Final Steps to Mastering JavaScript's 'this' Keyword

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
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

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);
}

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
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);
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));
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
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

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);
}
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
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
JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 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.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 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.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

In JavaScript, how to get parameters of a function on a prototype chain in a constructor?In JavaScript, how to get parameters of a function on a prototype chain in a constructor?Apr 04, 2025 pm 09:21 PM

How to obtain the parameters of functions on prototype chains in JavaScript In JavaScript programming, understanding and manipulating function parameters on prototype chains is a common and important task...

What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?Apr 04, 2025 pm 09:18 PM

Analysis of the reason why the dynamic style displacement failure of using Vue.js in the WeChat applet web-view is using Vue.js...

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor