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!