Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do immutable.js classes not require "new"?

For example, this is perfectly fine code. (The style is ES6)

import {List} from 'immutable';

console.log(List()); // List []

However, this fails.

class Foo {}

Foo(); // TypeError: Cannot call a class as a function

Further, this fails, too.

class Foo extends List {}

Foo(); // TypeError: Cannot call a class as a function
like image 572
almostflan Avatar asked Sep 16 '15 21:09

almostflan


1 Answers

Looks like the magic for immutable happens in their custom addon to the transpiler here.

They're basically creating their own createClass which skips the check. This is a snippet from the transpiled (via babel) version of my code above.

var Foo = (function (_List) {
  _inherits(Foo, _List);

  function Foo() {
    _classCallCheck(this, Board);

    _get(Object.getPrototypeOf(Foo.prototype), 'constructor', this).apply(this, arguments);
  }

  return Foo;
})(_immutable.List);

Where _classCallCheck looks like this.

function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError('Cannot call a class as a function');
    }
}

For immutable, it seems the ES6 code is first transformed to already include the createClass calls.

like image 140
almostflan Avatar answered Sep 23 '22 14:09

almostflan