Seeking to understand the binding of 'this' when a function is passed to the map
method of an array.
Code snippet available on StackBlitz:
import './style.css';
class Foo {
public method() { return this ? `"this" is a ${this.constructor.name}`
: '"this" is undefined'; }
}
class Caller {
public method1(array) {
return array.map(function() { return foo.method(); });
}
public method2(array) {
return array.map(this.callMethod);
}
public method3(array) {
return array.map(foo.method);
}
public method4(array) {
return array.map(v => foo.method());
}
private callMethod() { return foo.method(); }
}
const foo = new Foo();
const caller = new Caller();
const array = [1];
document.getElementById('app').innerHTML = `
<dl>
<dt>Expected</dt>
<dd>${foo.method()}</dd>
<dt>Method 1 (anonymous function)</dt>
<dd>${caller.method1(array)}</dd>
<dt>Method 2 (class method)</dt>
<dd>${caller.method2(array)}</dd>
<dt>Method 3 (function reference)</dt>
<dd>${caller.method3(array)}</dd>
<dt>Method 4 (lambda function)</dt>
<dd>${caller.method4(array)}</dd>
</dl>
`;
The output reveals that most methods result in 'this' bound to the Foo
object.
Confusion arises while referencing MDN's explanation of array.prototype.map
, which states:
If a thisArg parameter is provided to map, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value.
In none of the cases mentioned am I providing a thisArg
parameter explicitly - so why do 3 out of 4 methods "work"?
Bonus question: oddly, commenting out the first line (import './style.css'
) enables method 3 to work correctly. Any insights?