JavaScript绑定-箭头函数和绑定 [英] JavaScript binding - arrow functions and bind

查看:74
本文介绍了JavaScript绑定-箭头函数和绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

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 的处理方式不同.我知道它们保留了调用它们的原始上下文,在这种情况下,不包括x.但这还会阻止bind()工作吗?

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?

推荐答案

但这还会阻止bind()工作吗?

But does it also prevent bind() from working?

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

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不能更改箭头this的概念.它所能做的就是提供其辅助功能,即预先提供参数:

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

这篇关于JavaScript绑定-箭头函数和绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆