为什么immutable.js类不需要“new”?

时间:2015-09-16 21:51:09

标签: javascript ecmascript-6 immutable.js

例如,这是完美的代码。 (风格是ES6)

import {List} from 'immutable';

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

然而,这失败了。

class Foo {}

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

此外,这也失败了。

class Foo extends List {}

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

1 个答案:

答案 0 :(得分:9)

看起来immutable的魔力发生在他们对转录程序here的自定义插件中。

他们基本上创建了自己的createClass,它会跳过支票。这是我上面代码的已转换(通过babel)版本的片段。

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);

_classCallCheck看起来像这样。

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

对于immutable,似乎首先将ES6代码转换为已包含createClass次调用。