Why we don't need to bind the arrow function in React?

前端 未结 2 1420
遇见更好的自我
遇见更好的自我 2020-12-10 06:41

We all know that we need to bind function in React to make it work. I do know why do we need to bind it.

But I\'m not sure why we don\'t need to bind arrow function

2条回答
  •  情书的邮戳
    2020-12-10 07:21

    To quote MDN:

    An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

    Further,

    Until arrow functions, every new function defined its own this value (based on how function was called, a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.

    So basically, the reason we don't need to bind is because this does not exist in the context of the arrow function. So, it goes up to the next level and uses the this it finds there.

提交回复
热议问题