JavaScript double colon (bind operator)

JavascriptEcmascript HarmonyEcmascript Next

Javascript Problem Overview


As you know, there is a proposal for a shortcut for .bind() function, so you can write:

::this.handleStuff

and it will work like that in 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.

Javascript Solutions


Solution 1 - Javascript

No. The bind operator (spec proposal) comes in two flavours:

  • Method extraction

      ::obj.method     ≡ obj.method.bind(obj)
    
  • "virtual method" calls

      obj::functionfunction.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')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVictor MarchukView Question on Stackoverflow
Solution 1 - JavascriptBergiView Answer on Stackoverflow