ajhsu / blog

The external storage of my brain.
3 stars 0 forks source link

Digging into ES6 transpilation #92

Open ajhsu opened 5 years ago

ajhsu commented 5 years ago

The following piece of ES6 snippet:

class Foo {
  name = 'hello';
  get price() {
    return 999;
  }
}

Will be transpiled into following ES5 snippet:

var Foo =
  (function() {

    function Foo() {
      defineProperty(this, "name", "hello");
    }

    createClass(Foo, [{
      key: "price",
      get: function get() {
        return 999;
      }
    }]);

    return Foo;
  })();

function createClass(Constructor, protoProps, staticProps) {

  // Define the class properties onto prototype object.
  if (protoProps) defineProperties(Constructor.prototype, protoProps);

  // Define the static class properties onto Constructor itself.
  if (staticProps) defineProperties(Constructor, staticProps);

  return Constructor;
}

function defineProperty(obj, key, value) {

  if (key in obj) {

    // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });

  } else {
    obj[key] = value;
  }
  return obj;
}

function defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;

    if ("value" in descriptor) {
      descriptor.writable = true;
    }

    // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}