search
HomeWeb Front-endJS Tutorial5 ways to correctly handle the this pointer of JS

5 ways to correctly handle the this pointer of JS

I like to change the pointer of the function execution context in JS, also known as this pointer.

For example, we can use array methods on array-like objects:

const reduce = Array.prototype.reduce;

function sumArgs() {
  return reduce.call(arguments, (sum, value) => {
    return sum += value;
  });
}

sumArgs(1, 2, 3); // => 6

On the other hand, this is difficult to grasp.

We often find that we use this to point incorrectly. The following teaches you how to simply bind this to the desired value.

[Related course recommendations: JavaScript video tutorial]

Before I start, I need a helper function execute(func) that only executes the function provided as a parameter.

function execute(func) {
  return func();
}

execute(function() { return 10 }); // => 10

Now, moving on to understanding the nature of the error surrounding this: method separation.

1. Method separation problem

Suppose there is a class Person containing fields firstName and lastName. Additionally, it has a method getFullName() which returns the full name of the person. As shown below:

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;

  this.getFullName = function() {
    this === agent; // => true
    return `${this.firstName} ${this.lastName}`;
  }
}

const agent = new Person('前端', '小智');
agent.getFullName(); // => '前端 小智'

You can see that the Person function is called as a constructor: new Person('front end', 'Xiao Zhi'). This inside the function represents the newly created instance.

getfullname() returns the person's full name: 'front-end Xiaozhi'. As expected, this inside the getFullName() method is equal to agent.

What will happen if the auxiliary function executes the agent.getFullName method:

execute(agent.getFullName); // => 'undefined undefined'

The execution result is incorrect: 'undefined undefined', which is a problem caused by incorrect this pointing.

Now in the getFullName() method, the value of this is the global object (window in the browser environment). This is equal to window, and the execution result of ${window.firstName} ${window.lastName} is 'undefined undefined'.

This happens because the method is detached from the object when execute(agent.getFullName) is called. Basically what happens is just a regular function call (not a method call):

execute(agent.getFullName); // => 'undefined undefined'

// 等价于:

const getFullNameSeparated = agent.getFullName;
execute(getFullNameSeparated); // => 'undefined undefined'

This is what is called a method being detached from its object. When a method is detached and then executed, this has no connection to the original object.

1. In order to ensure that this inside the method points to the correct object, this must be done

2. Execute the method in the form of a property accessor: agent.getFullName() or bind this statically Determine the contained object (using arrow function, .bind() method, etc.)

Method separation problem, and the resulting incorrect this pointing, generally occur in the following situations:

Callback

// `methodHandler()`中的`this`是全局对象
setTimeout(object.handlerMethod, 1000);

When setting up the event handler

// React: `methodHandler()`中的`this`是全局对象
<button onClick={object.handlerMethod}>
  Click me
</button>

Then we introduce some useful methods, that is, if the method is separated from the object, How to make this point to the desired object.

2. Close the context

The simplest way to keep this pointing to the class instance is to use an additional variable self:

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  const self = this;
  this.getFullName = function() {
    self === agent; // => true
    return `${self.firstName} ${self.lastName}`;
  }
}
const agent = new Person(&#39;前端&#39;, &#39;小智&#39;);
agent.getFullName();        // => &#39;前端 小智&#39;
execute(agent.getFullName); // => &#39;前端 小智&#39;

getFullName() statically closes the self variable, effectively manually binding this.

Now, when calling execute(agent.getFullName), everything works fine because this inside the getFullName() method always points to the correct value.

3. Using arrow functions

Is there a way to statically bind this without additional variables? Yes, that's exactly what arrow functions do.

Use arrow functions to reconstruct Person:

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;

  this.getFullName = () => `${this.firstName} ${this.lastName}`;
}

const agent = new Person(&#39;前端&#39;, &#39;小智&#39;);

agent.getFullName();        // => &#39;前端 小智&#39;
execute(agent.getFullName); // => &#39;前端 小智&#39;

Arrow functions bind this lexically. Simply put, it uses the value from the external function this where it is defined.

It is recommended to use arrow functions in all cases where an external function context is required.

4. Binding context

Now let’s go one step further and reconstruct Person using classes in ES6.

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const agent = new Person('前端', '小智');

agent.getFullName();        // => '前端 小智'
execute(agent.getFullName); // => &#39;undefined undefined&#39;

Unfortunately, even with the new class syntax, execute(agent.getFullName) still returns "undefined undefined".

In the case of classes, using an additional variable self or an arrow function to fix the pointing of this will not work.

But there is a trick involving the bind() method, which binds the context of the method into the constructor:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;

    this.getFullName = this.getFullName.bind(this);
  }

  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const agent = new Person(&#39;前端&#39;, &#39;小智&#39;);

agent.getFullName();        // => &#39;前端 小智&#39;
execute(agent.getFullName); // => &#39;前端 小智&#39;

this.getFullName in the constructor = this.getFullName.bind( this) binds the method getFullName() to the class instance.

execute(agent.getFullName) works as expected, returning 'frontend Xiaozhi'.

5. Fat arrow method

bind method is a bit too lengthy, we can use the fat arrow method:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  getFullName = () => {
    return `${this.firstName} ${this.lastName}`;
  }
}

const agent = new Person(&#39;前端&#39;, &#39;小智&#39;);

agent.getFullName();        // => &#39;前端 小智&#39;
execute(agent.getFullName); // => &#39;前端 小智&#39;

Fat arrow method getFullName =() =>{…} is bound to a class instance, even if the method is detached from its object.

This method is the most effective and concise way to bind this in a class.

6. Summary

Methods separated from the object will cause the problem of incorrect this pointing. To bind this statically, you can manually use an additional variable self to hold the correct context object. However, a better alternative is to use arrow functions, which essentially serve to lexically bind this.

In a class, you can use the bind() method to manually bind the class method in the constructor. Of course, if you don't need to use the lengthy method of bind, you can also use the concise and convenient fat arrow representation method.

Original text: https://github.com/valentinogagliardi/Little-JavaScript-Book/blob/v1.0.0/manuscript/chapter5.md

This article comes from js tutorial Column, welcome to learn!

The above is the detailed content of 5 ways to correctly handle the this pointer of JS. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:fundebug. If there is any infringement, please contact admin@php.cn delete
如何使用JS和百度地图实现地图平移功能如何使用JS和百度地图实现地图平移功能Nov 21, 2023 am 10:00 AM

如何使用JS和百度地图实现地图平移功能百度地图是一款广泛使用的地图服务平台,在Web开发中经常用于展示地理信息、定位等功能。本文将介绍如何使用JS和百度地图API实现地图平移功能,并提供具体的代码示例。一、准备工作使用百度地图API前,首先需要在百度地图开放平台(http://lbsyun.baidu.com/)上申请一个开发者账号,并创建一个应用。创建完成

如何使用JS和百度地图实现地图多边形绘制功能如何使用JS和百度地图实现地图多边形绘制功能Nov 21, 2023 am 10:53 AM

如何使用JS和百度地图实现地图多边形绘制功能在现代网页开发中,地图应用已经成为常见的功能之一。而地图上绘制多边形,可以帮助我们将特定区域进行标记,方便用户进行查看和分析。本文将介绍如何使用JS和百度地图API实现地图多边形绘制功能,并提供具体的代码示例。首先,我们需要引入百度地图API。可以利用以下代码在HTML文件中导入百度地图API的JavaScript

js字符串转数组js字符串转数组Aug 03, 2023 pm 01:34 PM

js字符串转数组的方法:1、使用“split()”方法,可以根据指定的分隔符将字符串分割成数组元素;2、使用“Array.from()”方法,可以将可迭代对象或类数组对象转换成真正的数组;3、使用for循环遍历,将每个字符依次添加到数组中;4、使用“Array.split()”方法,通过调用“Array.prototype.forEach()”将一个字符串拆分成数组的快捷方式。

如何使用JS和百度地图实现地图热力图功能如何使用JS和百度地图实现地图热力图功能Nov 21, 2023 am 09:33 AM

如何使用JS和百度地图实现地图热力图功能简介:随着互联网和移动设备的迅速发展,地图成为了一种普遍的应用场景。而热力图作为一种可视化的展示方式,能够帮助我们更直观地了解数据的分布情况。本文将介绍如何使用JS和百度地图API来实现地图热力图的功能,并提供具体的代码示例。准备工作:在开始之前,你需要准备以下事项:一个百度开发者账号,并创建一个应用,获取到相应的AP

js中new操作符做了哪些事情js中new操作符做了哪些事情Nov 13, 2023 pm 04:05 PM

js中new操作符做了:1、创建一个空对象,这个新对象将成为函数的实例;2、将新对象的原型链接到构造函数的原型对象,这样新对象就可以访问构造函数原型对象中定义的属性和方法;3、将构造函数的作用域赋给新对象,这样新对象就可以通过this关键字来引用构造函数中的属性和方法;4、执行构造函数中的代码,构造函数中的代码将用于初始化新对象的属性和方法;5、如果构造函数中没有返回等等。

用JavaScript模拟实现打字小游戏!用JavaScript模拟实现打字小游戏!Aug 07, 2022 am 10:34 AM

这篇文章主要为大家详细介绍了js实现打字小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

php可以读js内部的数组吗php可以读js内部的数组吗Jul 12, 2023 pm 03:41 PM

php在特定情况下可以读js内部的数组。其方法是:1、在JavaScript中,创建一个包含需要传递给PHP的数组的变量;2、使用Ajax技术将该数组发送给PHP脚本。可以使用原生的JavaScript代码或者使用基于Ajax的JavaScript库如jQuery等;3、在PHP脚本中,接收传递过来的数组数据,并进行相应的处理即可。

js是什么编程语言?js是什么编程语言?May 05, 2019 am 10:22 AM

js全称JavaScript,是一种具有函数优先的轻量级,直译式、解释型或即时编译型的高级编程语言,是一种属于网络的高级脚本语言;JavaScript基于原型编程、多范式的动态脚本语言,并且支持面向对象、命令式和声明式,如函数式编程。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools