The basic usage of JavaScript this
keyword has been explained in the previous article. this
The 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 onthis
.
Common problems with -
this
Keywords include use in extracted methods, callback functions, and closures. These problems can be solved by explicitly binding thebind()
keyword to the correct object using thethis
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 thethis
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 usingcall()
,apply()
orbind()
.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
this
var car = { brand: "Nissan", getBrand: function() { console.log(this.brand); } }; var getCarBrand = car.getBrand; getCarBrand(); // 输出:undefinedseems 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
as an argument) as the callback function. For example: this
var getCarBrand = car.getBrand.bind(car); getCarBrand(); // 输出:NissanEven 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(); // 输出:undefinedThis 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
this
function
Rescue of ECMAScript 6=>
this
new
In the previous example, we see the so-called "lexical method var self = this;
" - when we assign 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
-
this
We 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. -
this
In 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
null
When a function is called usingthis
or or - ,
new
points to the first parameter passed to these methods. If the first parameter isthis
or is not an object, then points to the global object. -
this
When calling a function using the operator,
this
When using arrow functions (introduced in ECMAScript 6),
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.
this
this
Summary
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!

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

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.

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.

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

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

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


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

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
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor