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 the 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 the this
we use is incorrect. The following teaches you how to simply bind this
to the desired value.
Before I begin, I need a helper function execute(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 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 happens if the auxiliary function executes the agent.getFullName
method:
execute(agent.getFullName); // => 'undefined undefined'
The execution result is incorrect: 'undefined undefined'
, this isthis
Problem caused by incorrect pointing.
Now in the getFullName()
method, the value of this
is the global object (window
in the browser environment). this
is equal to window
, ${window.firstName} ${window.lastName}
The execution result 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 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 that this
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 of this
will generally occur in the following situations:
Callback
// `methodHandler()`中的`this`是全局对象 setTimeout(object.handlerMethod, 1000);
When setting up an event handler,
// React: `methodHandler()`中的`this`是全局对象 <button onClick={object.handlerMethod}> Click me </button>
then introduces some useful methods, that is, how to make this
point to the desired object if the method is detached from the object.
2. Close the context
The easiest 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('前端', '小智'); agent.getFullName(); // => '前端 小智' execute(agent.getFullName); // => '前端 小智'
getFullName()
statically closes the self
variable, effectively manually binding this
.
Now when calling execute(agent.getFullName)
everything works fine because getFullName()
inside the method this
always points to 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.
Refactoring using arrow functions Person
:
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 bind this
. Simply put, it uses the value from the external function this
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 refactoring Person
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 variable self
or an arrow function to fix what this
points to won't 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('前端', '小智'); agent.getFullName(); // => '前端 小智' execute(agent.getFullName); // => '前端 小智'
this in the constructor .getFullName = this.getFullName.bind(this)
Bind the method getFullName()
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!