Arrow functions in JavaScript do not have their own bindings of this. In other words, in an arrow function, this refers to the this object where the arrrow function is created. By contrast, this in an ordinary anonymous function does not refer to a fixed object.
For example, consider the following code:
let o = {
f1: function() { console.log(this.name); },
f2: () => { console.log(this.name); },
name: 'foo'
};
Under strict mode, o.f1() prints foo while o.f2 prints undefined, since f2 is created in the global level code and this is undefined (under non-strict mode, this refers to globalThis).
The following implementation is functionally equivalent to the code above: f2 never uses this, but accesses _this set by the outer scope code.
let o = {
f1: function() { console.log(this.name); },
f2: (function(_this) {
return function() {
console.log(_this.name);
}
})(this)
};
Leave a comment