Access to this in different types of Anonimas functions

Asked

Viewed 20 times

1

The question is simple, because when I do it:

function reducer(accumulator, current) {
    return accumulator.concat(current);
}

Array.prototype.flatMap = () => {
  return this.reduce(reducer, []);
};

The exception is made: this.reduce is not a function, but when I change to:

function reducer(accumulator, current) {
    return accumulator.concat(current);
}

Array.prototype.flatMap = function () {
  return this.reduce(reducer, []);
};

Everything works normally.

What I imagine should happen is: When passing the function to the Array prototype, it should bind the function automatically, regardless of whether it is anonymous or not. And apparently that doesn’t happen.

What I don’t understand is that since both are anonymous functions, both should inherit the this of the father scope, but for some reason only the first is inheriting, not the second, the this of it is the array itself, why? The bind of the first function should not be equal to the second?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.