双冒号运算符

箭头函数可以绑定this对象,大大减少了显式绑定this对象的写法(callapplybind)。但是,箭头函数并不适用于所有场合,所以现在有一个提案,提出了“函数绑定”(function bind)运算符,用来取代callapplybind调用。

函数绑定运算符是并排的两个冒号(::),双冒号左边是一个对象,右边是一个函数。该运算符会自动将左边的对象,作为上下文环境(即this对象),绑定到右边的函数上面。

  1. foo::bar;
  2. // 等同于
  3. bar.bind(foo);
  4. foo::bar(...arguments);
  5. // 等同于
  6. bar.apply(foo, arguments);
  7. const hasOwnProperty = Object.prototype.hasOwnProperty;
  8. function hasOwn(obj, key) {
  9. return obj::hasOwnProperty(key);
  10. }

如果双冒号左边为空,右边是一个对象的方法,则等于将该方法绑定在该对象上面。

  1. var method = obj::obj.foo;
  2. // 等同于
  3. var method = ::obj.foo;
  4. let log = ::console.log;
  5. // 等同于
  6. var log = console.log.bind(console);

如果双冒号运算符的运算结果,还是一个对象,就可以采用链式写法。

  1. import { map, takeWhile, forEach } from "iterlib";
  2. getPlayers()
  3. ::map(x => x.character())
  4. ::takeWhile(x => x.strength > 100)
  5. ::forEach(x => console.log(x));