The Final Steps to Mastering JavaScript's 'this' Keyword
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(); // 输出:undefined
, 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(); // 输出:Nissan
, 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);
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));
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
. 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); }
). 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!

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

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

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

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.

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 in JavaScript? When processing data, we often encounter the need to have the same ID...

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.

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

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