@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
  10. .call(obj, val)
  11. ::obj.func(val);
  12. // is equivalent to:
  13. obj.func.call(obj, val);

Example

Basic

  1. const box = {
  2. weight: 2,
  3. getWeight() {
  4. return this.weight;
  5. },
  6. };
  7. const { getWeight } = box;
  8. console.log(box.getWeight()); // prints '2'
  9. const bigBox = { weight: 10 };
  10. console.log(bigBox::getWeight()); // prints '10'
  11. // Can be chained:
  12. function add(val) {
  13. return this + val;
  14. }
  15. 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
  3. .querySelectorAll("a")
  4. ::map(node => node.href)
  5. ::filter(href => href.substring(0, 5) === "https");
  6. 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").transformSync("code", {
  2. plugins: ["@babel/plugin-proposal-function-bind"],
  3. });

References