我可以使用 Function.bind 保留默认值吗?如果没有,为什么?

Can I conserve the default this by using Function.bind ? If no, why?

假设我有一个函数:

function onSomethingChanged(field, evt) {
    this.validate(field, evt.target.value);
}

我有一个 React 组件:

<input onChanged={this.onSomethingChanged.bind(null, "username")} />
  1. 如果我将 null 作为 thisArg 传递,我的 this 是否守恒?
  2. 如果不是,我如何在不显式使用 this(不写 this.onSomethingChanged.bind(this, "username"))的情况下保存它。
  3. 如果不是 (再次),为什么 JavaScript 阻止它?有解决方法吗?

谢谢!

没有。这是传递给任何函数的第一个参数。通过传入 null,您表示这是 null。

改为这样做。

<input onChanged={this.onSomethingChanged.bind(this, "username")} />

不,函数的上下文 (this) 在 strict mode 中将是 null,在 non-strict 模式中是全局对象 (window)

如果您不喜欢 bind 方法,您可以使用 ES6 arrow functions 来处理:

<input onChanged={()=>this.onSomethingChanged("username")} />

或者如果您不喜欢括号:

<input onChanged={$=>this.onSomethingChanged("username")} />

其中 $ 是事件对象(可以替换为 e 或您喜欢的任何其他字符)。