JavaScript 双冒号(绑定运算符)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31220078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript double colon (bind operator)
提问by Victor Marchuk
As you know, there is a proposal for a shortcut for .bind()
function, so you can write:
如您所知,有一个.bind()
功能快捷方式的建议,因此您可以编写:
::this.handleStuff
and it will work like that in es5:
它会像在 es5 中那样工作:
this.handleStuff.bind(this)
My question is: will it be possible to pass arguments this way?
我的问题是:是否可以通过这种方式传递参数?
I mean a way of writing this with the aforementioned shortcut:
我的意思是用前面提到的快捷方式来写这个:
this.handleStuff.bind(this, 'stuff')
It's a pretty common pattern in React, so it would be nice to shorten it a little.
这是 React 中非常常见的模式,因此将其缩短一点会很好。
回答by Bergi
No. The bind operator(spec proposal) comes in two flavours:
Method extraction
::obj.method ≡ obj.method.bind(obj)
"virtual method" calls
obj::function ≡ function.bind(obj) obj::function(…) ≡ function.call(obj, …)
方法提取
::obj.method ≡ obj.method.bind(obj)
“虚拟方法”调用
obj::function ≡ function.bind(obj) obj::function(…) ≡ function.call(obj, …)
Neither of them feature partial application. For what you want, you should use an arrow function:
它们都没有部分应用功能。对于你想要的,你应该使用箭头函数:
(...args) => this.handleStuff('stuff', ...args) ≡ this.handleStuff.bind(this, 'stuff')