I was using Node 13.12.0. Consider the following code snippet:
const A = function () {
this.someArray = ['a', 'b', 'c'];
this.forEach = this.someArray.forEach;
}
const a = new A();
a.forEach(item => console.log(item)); // should print the content of the array, but got nothing
When running the code above, no output was given nor any error was thrown. When putting a breakpoint inside the forEach
callback, the breakpoint was not triggered.
But the code below does yield expected output:
const A = function () {
this.doSomething = () => {
console.log('hello');
};
};
const B = function () {
this.a = new A();
this.doSomething = this.a.doSomething;
};
const b = new B();
b.doSomething(); // prints 'hello'
I have checked other questions about forEach
but it seems that none of them relates to this question.
Is there any explaination why they behave differently?
I have suspected that it might because this
was different when called from different objects. But a quick check in a debugger turned out it was the same.
I also figured out that forEach
is a native function. Does this have something to do with the question?