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

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

Jennifer Aniston
Jennifer AnistonOriginal
2025-02-19 13:17:09490browse

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
<code class="language-javascript">var car = {
  brand: "Nissan",
  getBrand: function() {
    console.log(this.brand);
  }
};

var getCarBrand = car.getBrand;

getCarBrand(); // 输出:undefined</code>
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

<code class="language-javascript">var car = {
  brand: "Nissan",
  getBrand: function() {
    console.log(this.brand);
  }
};

var getCarBrand = car.getBrand;

getCarBrand(); // 输出:undefined</code>

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.

<code class="language-javascript">function(){
  console.log(this.brand);
}</code>

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

<code class="language-javascript">var getCarBrand = car.getBrand.bind(car);
getCarBrand(); // 输出:Nissan</code>
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

<code class="language-javascript">var car = {
  brand: "Nissan",
  getBrand: function() {
    console.log(this.brand);
  }
};

var el = document.getElementById("btn");
el.addEventListener("click", car.getBrand);</code>
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

<code class="language-javascript">el.addEventListener("click", car.getBrand.bind(car));</code>
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()

<code class="language-javascript">var car = {
  brand: "Nissan",
  getBrand: function() {
    var closure = function() {
      console.log(this.brand);
    };
    return closure();
  }
};

car.getBrand(); // 输出:undefined</code>
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

<code class="language-javascript">var car = {
  brand: "Nissan",
  getBrand: function() {
    console.log(this.brand);
  }
};

var getCarBrand = car.getBrand;

getCarBrand(); // 输出:undefined</code>

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
<code class="language-javascript">function(){
  console.log(this.brand);
}</code>
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