JavaScript binding - arrow functions and bind [duplicate]

試著忘記壹切 提交于 2019-12-13 15:40:25

问题


I have this bit of code:

const data = {
  x: "Target"
}

let bar = () => {
  console.log(this.x)
}

let final = bar.bind(data); 
final();

This code returns undefined. Here is the same code, but with non-arrow functions:

const data = {
  x: "Target"
}

let bar = function(){
  console.log(this.x)
}

let final = bar.bind(data); 
final();

This code works. I want to understand why the arrow function kept the binding from working. I know that they handle this differently. I know that they keep the original context in which they were called, which in this case does not include x. But does it also prevent bind() from working?


回答1:


But does it also prevent bind() from working?

Partially, because bind returns a new function that calls the original function with a specific this — but arrow functions don't use the this they're called with, they completely ignore it. Instead, they close over the this where they're defined.

bind on an arrow function can't change the arrow's concept of this. All it can do is its secondary feature, pre-supplying arguments:

"use strict";
function run() {
  const f = (a, b, c) => {
    console.log("this", this);
    console.log("a", a);
    console.log("b", b);
    console.log("c", c);
  };

  const fbound = f.bind({}, 1, 2, 3);
  f();
  fbound();
}
run();
.as-console-wrapper {
  max-height: 100% !important;£
}



回答2:


Arrow function takes precedence over bind. Whenever there are two or more different ways of setting this context, they are resolved in the following order: -arrow functions -new keyword -bind -call or apply



来源:https://stackoverflow.com/questions/50630044/javascript-binding-arrow-functions-and-bind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!