JavaScript绑定 - 箭头函数和绑定

时间:2018-05-31 17:49:11

标签: javascript binding

我有这段代码:

const data = {
  x: "Target"
}

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

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

此代码返回undefined。这是相同的代码,但使用非箭头函数:

const data = {
  x: "Target"
}

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

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

此代码有效。我想理解为什么arrow函数保持绑定不起作用。我知道他们处理这个的方式不同。我知道他们保留了调用它们的原始上下文,在这种情况下不包括x。但它是否也阻止bind()工作?

2 个答案:

答案 0 :(得分:6)

  

但它是否也阻止了bind()的工作?

部分地,因为bind返回一个新函数,该函数使用特定this调用原始函数 - 但箭头函数不使用它们被调用的this,它们完全是忽略它。相反,他们关闭定义它们的this

箭头函数上的

bind无法更改箭头的this概念。它所能做的就是它的第二个功能,预先提供参数:

"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;£
}

答案 1 :(得分:0)

箭头功能优先于bind。只要有两种或更多种不同的方法来设置此上下文,它们将按以下顺序解析: - 箭头功能 - 新关键字 -bind - 调用或申请

相关问题