Home >Web Front-end >JS Tutorial >Why Doesn't `bind()` Work with Arrow Functions?

Why Doesn't `bind()` Work with Arrow Functions?

DDD
DDDOriginal
2024-12-09 03:10:17872browse

Why Doesn't `bind()` Work with Arrow Functions?

Binding 'this' in Arrow Functions

Arrow functions, introduced in ES6, have become popular due to their concise syntax. However, one limitation of arrow functions is their inability to rebind 'this'. Unlike regular functions, arrow functions inherit their 'this' binding from the surrounding context at the time of definition.

In the example provided, the arrow function:

var f = () => console.log(this);

is defined within the global scope. Therefore, 'this' refers to the global window object, not to the 'o' object to which we attempt to bind the function:

var fBound = f.bind(o);
fBound(); // Logs the window object

To resolve this issue, do not use an arrow function. Instead, define a normal function:

var f = function() {
  console.log(this);
}.bind(o);

f(); // Logs the 'o' object

In this case, the 'this' binding is correctly set to the 'o' object because a normal function is used, allowing the binding to be reassigned.

The above is the detailed content of Why Doesn't `bind()` Work with Arrow Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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