Can you bind 'this' in an arrow function?

前端 未结 11 2281
囚心锁ツ
囚心锁ツ 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:40

    From the MDN:

    An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous.

    This means you cannot bind a value to this like you want.

    0 讨论(0)
  • 2020-11-22 03:40

    Normal bind:

    tag.on("Initialized", function(tag) {
       nodeValueChanged(tag, currentNode)
    }.bind(currentNode))
    

    Arrow function bind:

    tag.on("Initialized", (tag => { nodeValueChanged(tag, currentNode) }).bind(currentNode))
    
    0 讨论(0)
  • 2020-11-22 03:44

    I asked the same question a couple days ago.

    You cannot bind a value since the this is already binded.

    Binding different this scope to ES6 => function operator

    0 讨论(0)
  • 2020-11-22 03:47

    You cannot use bind to change the value of this inside an arrow function. However, you can create a new regular function that does the same thing as the old arrow function and then use call or bind to re-bind this as usual.

    We use an eval call here to recreate the arrow function you pass in as a normal function and then use call to invoke it with a different this:

    var obj = {value: 10};
    function arrowBind(context, fn) {
      let arrowFn;
      (function() {
        arrowFn = eval(fn.toString());
        arrowFn();
      }).call(context);
    }
    arrowBind(obj, () => {console.log(this)});

    0 讨论(0)
  • 2020-11-22 03:49

    Maybe this example help to you :

    let bob = {
       _name: "Bob",
       _friends: ["stackoverflow"],
       printFriends:(x)=> {
          x._friends.forEach((f)=> {
             console.log(x._name + " knows " + f);
          });
       }
    }
    
    bob.printFriends = (bob.printFriends).bind(null,bob);
    bob.printFriends();

    0 讨论(0)
提交回复
热议问题