乐闻世界logo
搜索文章和话题

Can you bind ' this ' in an arrow function?

1个答案

1

**In JavaScript, arrow functions differ from regular functions (such as function expressions or function declarations) in a key way: arrow functions do not bind their own this; instead, they capture the this value from their surrounding context and use it as their own this value.

Since arrow functions lack their own this binding, attempting to bind this within them is ineffective. For example, if you try to use .bind(), .call(), or .apply() methods to alter the this context of an arrow function, these methods will not achieve the expected binding effect.

Consider the following code snippet:

javascript
let group = { title: "Our Group", members: ["John", "Pete", "Alice"], showList() { this.members.forEach( (member) => { console.log(this.title + ': ' + member); } ); } }; group.showList();

In this example, the arrow function within showList inherits the this value from the showList method, which refers to the group object. Consequently, this.title inside the arrow function correctly points to group.title.

If we replace the arrow function with a regular function and use .bind(this), the outcome remains identical, but this is not due to .bind() being effective; rather, it is because regular functions require explicit binding of this:

javascript
showList() { this.members.forEach(function(member) { console.log(this.title + ': ' + member); }.bind(this)); // Using .bind(this) to bind `this` }

In summary, arrow functions do not support using .bind(), .call(), or .apply() methods to modify their this context; instead, they automatically capture the this value from the context where they are created. This characteristic simplifies and clarifies handling this, particularly in scenarios requiring consistent context maintenance.

2024年6月29日 12:07 回复

你的答案