JavaScript双冒号(绑定运算符)


129

如您所知,有一个.bind()功能快捷方式的建议,因此您可以编写:

::this.handleStuff

它将在es5中像这样工作:

this.handleStuff.bind(this)

我的问题是:是否可以通过这种方式传递参数?

我的意思是用上述快捷方式编写此代码的方法:

this.handleStuff.bind(this, 'stuff')

这是React中很常见的模式,因此最好将其缩短一点。


1
您是在谈论部分申请吗?
— 本·阿斯顿

对于另一个规范建议来说,这似乎是个好主意。
— Greg Herbowicz

Answers:


154

否。bind运算符(规范建议)有两种形式:

  • 方法提取

    ::obj.method     ≡ obj.method.bind(obj)
  • “虚拟方法”调用

    obj::function    ≡ function.bind(obj)
    obj::function(…) ≡ function.call(obj, …)

它们都不具有部分应用的功能。对于您想要的,应该使用箭头功能:

(...args) => this.handleStuff('stuff', ...args) ≡ this.handleStuff.bind(this, 'stuff')

4
(有关支持部分申请的讨论)
— Bergi,2016年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.