I'm confused about the concept of JavaScript this binding, could you help me?

Asked 2 years ago, Updated 2 years ago, 91 views

Hello, I am a college student who started studying JavaScript recently.

I'm asking you a question because there's a problem that can't be solved by myself.

While studying the arrow function in JavaScript, I saw the example below.

class Prefixer {
  constructor(prefix) {
    this.prefix = prefix;
  }

  add(arr) {
    return arr.map((item) => this.prefix + item);
  }
}

const prefixer = new Prefixer("-webkit-");
console.log(prefixer.add(["transition", "user-select"]));

This is an example of outputting transition, user-select with a -webkit- prefix, and the arrow function shows that it does not have its own this binding and gets this from the parent scope.

But I understand everything else, and I don't know why this of the parent scope that the arrow function takes is the same as this of the Prefixer class.

I think calling the arrow function is a higher order function, arr.map, so the upper scope of the arrow function should be the scope of arr.map, and since map was called by arr's method, this in map should point to arr, and this in arrow function should point to arr.

I'm asking because I don't know why I get this result even if I try to modify and execute the code a few times.

There are two things I'm curious about.

Thank you for reading this long article.

javascript this

2022-09-19 23:22

1 Answers

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#description

For functions specified by arrows, they do not have their own scope. You will automatically receive this of the scope that defined the function.


2022-09-19 23:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.