Javascript 此绑定在forEach arrow函数中未按预期工作

Javascript 此绑定在forEach arrow函数中未按预期工作,javascript,Javascript,我有一个类,我在其中绑定构造函数中的一些函数。这很好,正如预期的那样 class Row { constructor(props) { super(props) this.onEditRowClick = this.onEditRowClick.bind(this) this.onCommitRowClick = this.onCommitRowClick.bind(this) this.onDeleteRowClick = this.onDeleteRowC

我有一个类,我在其中绑定构造函数中的一些函数。这很好,正如预期的那样

class Row {
  constructor(props) {
    super(props)
    this.onEditRowClick = this.onEditRowClick.bind(this)
    this.onCommitRowClick = this.onCommitRowClick.bind(this)
    this.onDeleteRowClick = this.onDeleteRowClick.bind(this)
    this.onCellChange = this.onCellChange.bind(this)
  }
  ...
}
但是,如果我改为

class Row {
  constructor(props) {
    super(props)

    let handlers = [this.onEditRowClick, this.onCommitRowClick, this.onCellChange, this.onDeleteRowClick]
    handlers.forEach(handler => {handler = handler.bind(this)})
  }
  ...
}
它显然不起作用,因为我得到了异常,表明我的函数调用中的
null

我认为arrow函数实现了一个词法
this
绑定

还有,如果我这样做

class Row {
  constructor(props) {
    super(props)

    [this.onEditRowClick, this.onCommitRowClick, this.onCellChange, this.onDeleteRowClick].forEach(handler => {handler = handler.bind(this)})
  }
}
我明白了

我完全可以

[1,2,3].forEach(function(item){console.log(item)})
也许我错过了一些非常明显的东西,该睡觉了?

从绑定到传递上下文的现有函数创建新函数。因此,您可以在第一个工作示例中重新分配属性:

this.onEditRowClick = this.onEditRowClick.bind(this);
但是,在后一个示例中,您跳过了重新分配阶段。 要解决此问题,您可以迭代方法名称,将其绑定到
this
实例并重新分配:

class Row {
  constructor(props) {
    super(props);

    let handlers = [
      'onEditRowClick',
      'onCommitRowClick',
      'onCellChange',
      'onDeleteRowClick'
    ];

    handlers.forEach(handler => {
        this[handler] = this[handler].bind(this);
    });
  }
  ...
}

嘿,谢谢!你的答案有效。但是,有一件事我无法理解……当我执行
[this.onEditRowClick,
时,我不是在数组中存储对函数的引用,以便
handler=>{handler=handler.bind(this)}
应该足够了?事实上,我认为引用的工作方式,不能从引用的角度重新分配源本身,只能改变其内部,是吗?在
handler=handler.bind上(这个)
您不是在
行实例
上重新分配实例方法,而是在
forEach
范围内重新分配时态变量
处理程序
的值。希望这有助于更好地理解此解决方案的原因works@sminutoli,确实如此。我正在更改数组实例,而不是
实例。感谢大家的帮助!:-)您正在重新分配参数。这不会更改传递到函数中的变量/属性的值。举个简单的例子:
var foo=42;(函数(bar){bar=21;}(foo))
foo
仍然具有值
42
。实际上,数组本身已经存在这个问题。再一个简化示例:
var foo=42;var bar=[foo];bar[0]=21;
foo
仍然具有值
42
class Row {
  constructor(props) {
    super(props);

    let handlers = [
      'onEditRowClick',
      'onCommitRowClick',
      'onCellChange',
      'onDeleteRowClick'
    ];

    handlers.forEach(handler => {
        this[handler] = this[handler].bind(this);
    });
  }
  ...
}