Differing behaviour of `Array.forEach` between when arguments are or aren't provided to anonymous function [closed]
Consider the following snippet:
class ThingPrinter {
printThing(thing) {
console.log(thing.val);
}
}
class Thing {
constructor(val) {
this.val = val;
}
}
const myThings = [new Thing("foo"), new Thing("bar")];
const thingPrinterInst = new ThingPrinter();
myThings.forEach((t) => thingPrinterInst.printThing(t));
myThings.forEach(thingPrinterInst.printThings);I would have expected the bottom two lines to be equivalent, and for the output to be:
foo
bar
foo
bar
However, in fact I get an exception from the final line (after one set of output):
myThings.forEach(thingPrinterInst.printThings);
^
TypeError: undefined is not a function
at Array.forEach (<anonymous>)
at Object.<anonymous> (/private/tmp/forEachDemo/main.js:20:10)
...
It seems that this behaviour only arises when referring to a method on an existing class, rather than a globally-available function. The following, for instance, works fine:
function printYourself(thing) {
console.log(thing.val);
}
class Thing {
constructor(val) {
this.val = val;
}
}
const myThings = [new Thing("foo"), new Thing("bar")];
myThings.forEach(printYourself);
I note from the docs and some examples that the callback is called with three parameters (element, index, and array) - but, if this undefined error is actually indicating "there is no implementation of thingPrinterInst.printThing which takes 3 arguments", then I don't see how the penultimate line (mythings.forEach((t) => thingPrinterInst.printThing(t));) can pass, either? (And, in any case - I tried changing the implementation of printThing to have 3 arguments, and the same behaviour was displayed)
Comments
Post a Comment