Reality-Loop

JavaScript Tip - Binding functions in ES.next

April 06, 2016 | 2 Minute Read

The “Function Bind Syntax” is a proposal for a new language feature of ECMAScript which allows you to bind functions to a context in an elegant way:

function sayHello(peer) { console.log('Hello to ' + peer.name + ' from ' + this.name)}

let universe = {name: 'universe'};
let world = {name: 'world'};

world::sayHello(universe); // -> Hello to universe from world
universe::sayHello(world); // -> Hello to world from universe

Currently the “Function Bind Syntax” proposal is at stage 0 of the specification process.

However Babel already supports that feature if you configure the stage-0 preset or the transform-function-bind plugin.

You can also try the above code in the online Babel REPL.

One of the main advantages of this syntax would be to provide “extension methods” like this:

import { take } from "trine/iterable/take";
import { to } from "trine/iterable/to";

let evenFilter = function() { return this % 2 === 0; };
let array = [1, 2, 3, 4];

let filtered = array::take(evenFilter);

console.log(filtered::to(Array)); // -> [ 2, 4 ]

The above code is using the trine library.

The current version of RxJs seems already to support the function bind syntax!

I have seen this features for the first time in the presentation “RxJS Version 5” by Ben Lesh.

A deeper discussion can be found in this blog post: JavaScript ES7 Function Bind Syntax

Here is the discussion about implementing the feature in TypeScript.