Several ways to handle 'this' pointer in JS

Release: 2020-06-18 17:18:03
forward
1904 people have browsed it

Several ways to handle 'this' pointer in JS

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

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
Copy after login

On the other hand,thisis difficult to grasp.

We often find that thethiswe use is incorrect. The following teaches you how to simply bindthisto the desired value.

Before I begin, I need a helper functionexecute(func)that simply executes the function provided as an argument.

function execute(func) { return func(); } execute(function() { return 10 }); // => 10
Copy after login

Now, moving on to understanding the essence of the error surroundingthis: method separation.

1. Method separation problem

Suppose there is a classPersoncontaining fieldsfirstNameandlastName. Additionally, it has a methodgetFullName(), 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(); // => '前端 小智'
Copy after login

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

getfullname()Returns the person's full name:'Front-end Xiaozhi'. As expected,thisinside thegetFullName()method is equal toagent.

What happens if the auxiliary function executes theagent.getFullNamemethod:

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

The execution result is incorrect:'undefined undefined', this isthisProblem caused by incorrect pointing.

Now in thegetFullName()method, the value ofthisis the global object (windowin the browser environment).thisis equal towindow,${window.firstName} ${window.lastName}The execution result is'undefined undefined'.

This happens because the method is detached from the object whenexecute(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'
Copy after login

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

In order to ensure thatthisinside the method points to the correct object, this must be done

  1. Execute the method as a property accessor:agent.getFullName()

  2. Or statically bindthisto the containing object (using arrow functions,.bind()method, etc.)

method separation problem , and the resulting incorrect pointing ofthiswill generally occur in the following situations:

Callback

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

When setting up an event handler,

// React: `methodHandler()`中的`this`是全局对象 
Copy after login

then introduces some useful methods, that is, how to makethispoint to the desired object if the method is detached from the object.

2. Close the context

The easiest way to keepthispointing to the class instance is to use an additional variableself:

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('前端', '小智'); agent.getFullName(); // => '前端 小智' execute(agent.getFullName); // => '前端 小智'
Copy after login

getFullName()statically closes theselfvariable, effectively manually bindingthis.

Now when callingexecute(agent.getFullName)everything works fine becausegetFullName()inside the methodthisalways points to correct value.

3. Using arrow functions

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

Refactoring using arrow functionsPerson:

function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.getFullName = () => `${this.firstName} ${this.lastName}`; } const agent = new Person('前端', '小智'); agent.getFullName(); // => '前端 小智' execute(agent.getFullName); // => '前端 小智'
Copy after login

Arrow functions lexically bindthis. Simply put, it uses the value from the external functionthisit is defined in.

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 use the class refactoringPersonin 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); // => 'undefined undefined'
Copy after login

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

In the case of a class, using an additional variableselfor an arrow function to fix whatthispoints to won't work.

But there is a trick involving thebind()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('前端', '小智'); agent.getFullName(); // => '前端 小智' execute(agent.getFullName); // => '前端 小智'
Copy after login

this in the constructor .getFullName = this.getFullName.bind(this)Bind the methodgetFullName()to the class instance.

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

5. Fat arrow method

#bindThe 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('前端', '小智'); agent.getFullName(); // => '前端 小智' execute(agent.getFullName); // => '前端 小智'
Copy after login

胖箭头方法getFullName =() =>{…}绑定到类实例,即使将方法与其对象分离。

这种方法是在类中绑定this的最有效和最简洁的方法。

6. 总结

与对象分离的方法会产生 this 指向不正确问题。静态地绑定this,可以手动使用一个附加变量self来保存正确的上下文对象。然而,更好的替代方法是使用箭头函数,其本质上是为了在词法上绑定this

在类中,可以使用bind()方法手动绑定构造函数中的类方法。当然如果你不用使用bind这种冗长方式,也可以使用简洁方便的胖箭头表示方法。

更多JavaScript知识请关注PHP中文网JavaScript视频教程栏目

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

Related labels:
source:csdn.net
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!