函数绑定语法
· 1 分钟阅读
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
Babel 5.4 刚刚发布,新增了对 Kevin Smith (@zenparsing) 提出的全新 实验性 ES7 语法的支持, 该功能由 Ingvar Stepanyan (@RReverser) 在 Babel 中实现。
警告:此语法仍处于高度实验阶段,请勿在正式项目中使用(目前)。 若您尝试使用此语法, 请在 GitHub 提供反馈。
函数绑定语法引入了一个新运算符 ::,用于执行函数绑定和方法提取。
虚拟方法
使用通过"虚拟方法"模块实现的迭代器库示例:
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 的虚拟方法库示例:
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");
方法提取
使用方法提取将 Promise 的最终值打印到控制台:
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 事件发生时调用对象方法:
JavaScript
/* ES7 */
$(".some-link").on("click", ::view.reset);
JavaScript
/* ES6 */
$(".some-link").on("click", view.reset.bind(view));
注意: 您可以在 函数绑定语法提案中查看更多相关信息。
使用方式
按阶段启用:
Shell
$ babel --stage 0
通过转换器启用:
Shell
$ babel --optional es7.functionBind
此函数绑定语法需获得足够关注才能纳入 ES7 规范。 若您希望此语法被采纳,请在 GitHub 为其点赞(star), 并通过 GitHub issues 提供反馈。
特别感谢 Ingvar Stepanyan (@RReverser) 在 Babel 中的实现。
— The Babel team