Detailed explanation of this pointing problem in JavaScript

Detailed explanation of this pointing problem in JavaScript

Preface

The this pointer in JS has always been a headache for beginners. Today, let’s take a look at what happened when this fell to the ground, and talk about the this pointing principle in detail, so that we will no longer worry about the this pointing.

Introduction

First of all, we all know that this is a keyword in the Javascript language.

It represents an internal object that is automatically generated when the function is running and can only be used within the function. The value of this will change depending on where the function is used. However, there is a general principle, that is, the direction of this cannot be determined when the function is defined. Only when the function is executed can it be determined who this actually points to. In fact, this ultimately points to the object that calls the function in which it is located. So let’s explore this issue step by step.

Explore One

function a() {
  var user = "Steamed Bighead Carp";
  console.log(this.name); //undefined
  console.log(this); //Window
 }
 a();
 window.a(); //The two results are the same

As we said above, this ultimately points to the object that calls the function in which it is located. Here, a is actually pointed out by the window object.

Exploration 2

var obj = {
  name: 'Steamed Fathead Fish',
  f1: function () {
   console.log(this.name); //Steamed bighead carp}
 };
 obj.f1();

It is important to emphasize again that the direction of this cannot be determined when the function is defined. Only when the function is executed can we determine who this is pointing to. In this example, the f1 function where this is located is called by the obj object, so this here points to the obj object.

Exploration Three

If you want to fully understand this, you must look at the following examples.

var obj = {
  a: 5,
  b: {
   a: 10,
   fn: function () {
    console.log(this.a); //10
   }
  }
 };
 obj.b.fn();

Doesn't it mean that this ultimately refers to the object that calls the function in which it is located? Why doesn't this point to the obj object?

Three points need to be added here:

  1. If a function has this, but it is not called by the parent object, then this refers to window.
  2. If a function has this and is called by an object at the previous level, then this refers to the object at the previous level.
  3. If a function has this and contains multiple objects, even though the function is called by the outermost object, this only points to the object one level above it.

Seeing this, I believe everyone has basically grasped the principle of this pointing. Let me repeat it again: the pointing of this cannot be determined when the function is defined. Only when the function is executed can we determine who this actually points to. In fact, this ultimately points to the object that calls the function in which it is located.

Here are some different usage scenarios for this

Constructor (new keyword) case

function Student() {
  this.name = 'Steamed Fathead Fish';
 }
 var s1 = new Student();
 console.log(s1.name); // Steamed bighead carp

The reason why object s1 can point to the name in the function Student is because the new keyword can change the pointer of this to point to object s1.

// The execution process of the new keyword 1. Create an empty object in the function body.
 2. Let the current this point to this empty object.
 3. Add key-value pairs to the currently empty object through this.
 4. Return the object with all key-value pairs added to the external variable.

The this pointer in the timer

var num = 0;
 function Obj() {
  this.num = 1;
  this.getNum1 = function () {
   console.log(this.num);
  };
  this.getNum2 = function () {
   setInterval(function () {
    console.log(this.num);
   }, 1000);
  };
 }
 var o = new Obj();
 o.getNum1();//1 (o.num)
 o.getNum2();//0 (window.num)

The reason why the value of o.getNum2() is 0 is that this here points to window . Let's take out our this pointing principle to explain: the pointing of this cannot be determined when the function is defined. Only when the function is executed can we determine who this actually points to. In fact, this ultimately points to the object that calls the function in which it is located.

Solution: The function where this.num is located is function () { console.log(this.num);} in the timer setInterval . According to the this pointing principle, when the function is executed, this points to its parent object. setInterval , and because setInterval is pointed out by window , this points to window .

call , apply , bind change the direction

var num = 0;
 function Obj() {
  this.num = 1;
  this.getNum1 = function () {
   console.log(this.num);
  };
  this.getNum2 = function () {
   setInterval(function () {
    console.log(this.num);
   }.bind(this), 1000);//Use bind to bind this to this function};
 }
 var o = new Obj();
 o.getNum1();//1 (o.num)
 o.getNum2();//1 (o.num)
 

explain:

The bind() method is a method on Function.prototype. When called by a bound function, the bind method creates a new function and uses the first parameter as the runtime this of the new function.

According to the principles:

Before using the bind method: When called: this.num points to the object that calls the function in which it is located, that is, the window.setTimeout object. After using the bind method: when called: the original this is redirected to the object that calls the getSum2 function (the function where the new this is located). Here the constructor is called through new , so it points to the o object.

bind method is more commonly used in this situation. Of course, if you use call or apply method instead, the result is also correct, but call and apply methods will be executed immediately after the call, so there will be no delay effect, and the timer will be meaningless.

The above is a detailed explanation of the this pointing problem in JavaScript. For more information about JavaScript this pointing, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • JavaScript this points to related issues and how to change them
  • Detailed explanation of JavaScript's this pointing and binding
  • What I understand about this in JavaScript
  • JavaScript this keyword points to common case analysis
  • A brief discussion on the pointing problem of this in JavaScript
  • A brief discussion on the change of this in JavaScript
  • JavaScript this points to the relevant principles and examples
  • Detailed explanation of JavaScript This pointing problem
  • A brief discussion on several easy ways to handle ''this'' in JS
  • Detailed explanation of the pointing problem of this in js

<<:  MySQL optimization connection optimization

>>:  Tutorial on adjusting the size of lvm logical volume partition in Linux (for different file systems such as xfs and ext4)

Recommend

Table related arrangement and Javascript operation table, tr, td

Table property settings that work well: Copy code ...

Let’s take a look at JavaScript precompilation (summary)

JS running trilogy js running code is divided int...

What are mysql dirty pages?

Table of contents Dirty pages (memory pages) Why ...

How to start a transaction in MySQL

Preface This article mainly introduces how to sta...

Install Docker on Centos7 (2020 latest version available, just copy and paste)

Refer to the official documentation here for oper...

Docker connection mongodb implementation process and code examples

After the container is started Log in to admin fi...

MySQL GTID comprehensive summary

Table of contents 01 Introduction to GTID 02 How ...

MySQL data analysis storage engine example explanation

Table of contents 1. Introduce cases 2. View the ...

Linux View File System Type Example Method

How to check the file system type of a partition ...

VUE render function usage and detailed explanation

Table of contents Preface The role of render Rend...

A brief discussion on MySQL user permission table

MySQL will automatically create a database named ...

Simple Mysql backup BAT script sharing under Windows

Preface This article introduces a simple BAT scri...

Vue3 navigation bar component encapsulation implementation method

Encapsulate a navigation bar component in Vue3, a...