Home>Article>Web Front-end> Several ways to handle 'this' pointer in JS
I like to change the pointer of the function execution context in JS, also known as thethis
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 thethis
we use is incorrect. The following teaches you how to simply bindthis
to 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
Now, moving on to understanding the essence of the error surroundingthis
: method separation.
1. Method separation problem
Suppose there is a classPerson
containing fieldsfirstName
andlastName
. 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(); // => '前端 小智'
You can see that thePerson
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 thegetFullName()
method is equal toagent
.
What happens if the auxiliary function executes theagent.getFullName
method:
execute(agent.getFullName); // => 'undefined undefined'
The execution result is incorrect:'undefined undefined'
, this isthis
Problem caused by incorrect pointing.
Now in thegetFullName()
method, the value ofthis
is the global object (window
in the browser environment).this
is 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'
This is what is called when a method is detached from its object. When a method is detached and then executed,this
There is no connection to the original object.
In order to ensure thatthis
inside the method points to the correct object, this must be done
Execute the method as a property accessor:agent.getFullName()
this
to the containing object (using arrow functions,.bind()
method, etc.)method separation problem , and the resulting incorrect pointing ofthis
will generally occur in the following situations:
Callback
// `methodHandler()`中的`this`是全局对象 setTimeout(object.handlerMethod, 1000);
When setting up an event handler,
// React: `methodHandler()`中的`this`是全局对象
then introduces some useful methods, that is, how to makethis
point to the desired object if the method is detached from the object.
2. Close the context
The easiest way to keepthis
pointing 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); // => '前端 小智'
getFullName()
statically closes theself
variable, effectively manually bindingthis
.
Now when callingexecute(agent.getFullName)
everything works fine becausegetFullName()
inside the methodthis
always points to correct value.
3. Using arrow functions
Is there a way to statically bindthis
without 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); // => '前端 小智'
Arrow functions lexically bindthis
. Simply put, it uses the value from the external functionthis
it 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 refactoringPerson
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); // => 'undefined undefined'
Unfortunately, even with the new class syntax,execute(agent.getFullName)
still returns"undefined undefined"
.
In the case of a class, using an additional variableself
or an arrow function to fix whatthis
points 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); // => '前端 小智'
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
#bind
The 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); // => '前端 小智'
胖箭头方法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!