Skip to main content

函数绑定语法

· 4 min read

Babel 5.4 刚刚发布,随之而来的是对 Kevin Smith (@zenparsing) 提出的新实验性 ES7 语法 的支持,并由 Ingvar Stepanyan (@RReverser) 在 Babel 中实现。

🌐 Babel 5.4 was just released and with it comes support for a new experimental ES7 syntax proposed by Kevin Smith (@zenparsing) and implemented in Babel by Ingvar Stepanyan (@RReverser).

警告:这个语法仍处于高度实验阶段,你目前不应该在任何重要场合使用。 如果你确实使用了这个语法,请在GitHub提供反馈。

函数绑定语法引入了一个新的操作符 ::,它可以执行函数绑定和方法提取。

🌐 The function bind syntax introduces a new operator :: which performs function binding and method extraction.

虚方法​

🌐 Virtual Methods

使用作为“虚拟方法”模块实现的迭代器库:

🌐 Using an iterator library implemented as a module of "virtual methods":

JavaScript
/* ES7 */
import { map, takeWhile, forEach } from "iterlib";

getPlayers()
::map(x => x.character())
::takeWhile(x => x.strength > 100)
::forEach(x => console.log(x));
JavaScript
/* ES6 */
import { map, takeWhile, forEach } from "iterlib";

let _val;
_val = getPlayers();
_val = map.call(_val, x => x.character());
_val = takeWhile.call(_val, x => x.strength > 100);
_val = forEach.call(_val, x => console.log(x));

注意: Babel 的 输出 看起来与此不同,以便更简洁。

使用类似 jquery 的虚拟方法库:

🌐 Using a jquery-like library of virtual methods:

JavaScript
/* ES7 */
// Create bindings for just the methods that we need
let { find, html } = jake;

// Find all the divs with class="myClass", then get all of the
// "p"s and replace their content.
document.querySelectorAll("div.myClass")::find("p")::html("hahaha");
JavaScript
/* ES6 */
let _val;
_val = document.querySelectorAll("div.myClass");
_val = find.call(_val, "p");
_val = html.call(_val, "hahaha");

方法提取​

🌐 Method Extraction

使用方法提取将 promise 的最终值打印到控制台:

🌐 Using method extraction to print the eventual value of a promise to the console:

JavaScript
/* ES7 */
Promise.resolve(123).then(::console.log);
JavaScript
/* ES6 */
// Which could be written in ES6 as:
Promise.resolve(123).then(console.log.bind(console));

当 DOM 事件发生时,使用方法提取来调用对象方法:

🌐 Using method extraction to call an object method when a DOM event occurs:

JavaScript
/* ES7 */
$(".some-link").on("click", ::view.reset);
JavaScript
/* ES6 */
$(".some-link").on("click", view.reset.bind(view));

**注意:**你可以在函数绑定语法提案中了解更多关于这种语法的信息。

用法​

🌐 Usage

按阶段启用:

🌐 Enable by stage:

Shell
$ babel --stage 0

通过转换器启用:

🌐 Enable by transformer:

Shell
$ babel --optional es7.functionBind

只有在有足够兴趣的情况下,函数绑定语法才会进入 ES7。如果你希望看到这个语法被采纳,请在 GitHub 上给它点个星,并在 GitHub issues 上提供你的反馈。

🌐 The function bind syntax will only make it into ES7 if there is enough interest. If you would like to see this syntax make it in, please give it a star on GitHub and provide any feedback you have on GitHub issues.

特别感谢 Ingvar Stepanyan (@RReverser) 在 Babel 中的 实现。

🌐 Special thanks to Ingvar Stepanyan (@RReverser) for the implementation in Babel.

—— 巴别团队