Binding different this scope to ES6 => function operator

后端 未结 2 1097
走了就别回头了
走了就别回头了 2021-02-09 13:04

After experimenting with inheriting contexts with the => feature that ES6 gives us I noticed that the this context can never be changed. Example:

var otherConte         


        
2条回答
  •  清酒与你
    2021-02-09 13:15

    When using the function keyword, the rules binding this are fairly straight forward.

    Either the invoking call sets this (be it through .call, .apply or JavaScript setting this when the function is called as a method) or this gets a well-known value:

    • In normal mode, this will be the window object.
    • In strict mode, this will be undefined.

    With arrow functions, the rule is even simpler.

    • There is no this keyword. (nor arguments, or a few others)

    Which means that, inside an arrow function, this is always bound to the outside context, because that is where this comes from.

    So, in summary:

    When using arrow functions, the value of this always comes from the outside context.

提交回复
热议问题