Can you bind 'this' in an arrow function?

前端 未结 11 2283
囚心锁ツ
囚心锁ツ 2020-11-22 03:09

I\'ve been experimenting with ES6 for a while now, and I\'ve just come to a slight problem.

I really like using arrow functions, and whenever I can, I use them.

11条回答
  •  既然无缘
    2020-11-22 03:36

    Short, You CANNOT bind arrow functions, but read on:

    Imagine you have this arrow function below which prints this on the console:

    const myFunc = ()=> console.log(this);
    

    So the quick fix for this would be using normal function, so just change it to:

    function myFunc() {console.log(this)};
    

    Then you can bind it to any lexical environment using bind or call or apply:

    const bindedFunc = myFunc.bind(this);
    

    and call it in case of bind.

    bindedFunc();
    

    There are also ways to using eval() to do it, which strongly not recommended.

提交回复
热议问题