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

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

DDD
Release: 2024-12-09 03:10:17
Original
819 people have browsed it

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

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

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

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template