@babel/plugin-proposal-function-bind

Detail

  1. obj::func
  2. // is equivalent to:
  3. func.bind(obj)
  4. ::obj.func
  5. // is equivalent to:
  6. obj.func.bind(obj)
  7. obj::func(val)
  8. // is equivalent to:
  9. func.call(obj, val)
  10. ::obj.func(val)
  11. // is equivalent to:
  12. obj.func.call(obj, val)

Example

Basic

  1. const box = {
  2. weight: 2,
  3. getWeight() { return this.weight; },
  4. };
  5. const { getWeight } = box;
  6. console.log(box.getWeight()); // prints '2'
  7. const bigBox = { weight: 10 };
  8. console.log(bigBox::getWeight()); // prints '10'
  9. // Can be chained:
  10. function add(val) { return this + val; }
  11. console.log(bigBox::getWeight()::add(5)); // prints '15'

Using with document.querySelectorAll

It can be very handy when used with document.querySelectorAll:

  1. const { map, filter } = Array.prototype;
  2. let sslUrls = document.querySelectorAll('a')
  3. ::map(node => node.href)
  4. ::filter(href => href.substring(0, 5) === 'https');
  5. console.log(sslUrls);

document.querySelectorAll returns a NodeList element which is not a plain array, so you normally can't use the map function on it, and have to use it this way: Array.prototype.map.call(document.querySelectorAll(…), node => { … }). The above code using the :: will work because it is equivalent to:

  1. const { map, filter } = Array.prototype;
  2. let sslUrls = document.querySelectorAll('a');
  3. sslUrls = map.call(sslUrls, node => node.href);
  4. sslUrls = filter.call(sslUrls, href => href.substring(0, 5) === 'https');
  5. console.log(sslUrls);

Auto self binding

When nothing is specified before the :: operator, the function is bound to its object:

  1. $('.some-link').on('click', ::view.reset);
  2. // is equivalent to:
  3. $('.some-link').on('click', view.reset.bind(view));

Installation

  1. npm install --save-dev @babel/plugin-proposal-function-bind

Usage

  1. {
  2. "plugins": ["@babel/plugin-proposal-function-bind"]
  3. }

Via CLI

  1. babel --plugins @babel/plugin-proposal-function-bind script.js

Via Node API

  1. require("@babel/core").transform("code", {
  2. plugins: ["@babel/plugin-proposal-function-bind"]
  3. });

References