admin管理员组

文章数量:1414946

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

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
Share Improve this question asked Sep 16, 2015 at 21:51 almostflanalmostflan 6404 silver badges15 bronze badges 11
  • 1 Probably because they're not constructed using class? Or the ES6 transpiler was in loose mode. – Bergi Commented Sep 16, 2015 at 21:54
  • In what environment are you executing this, which immutable version are you using? – Bergi Commented Sep 16, 2015 at 21:55
  • immutable version is 3.7.5 – almostflan Commented Sep 16, 2015 at 21:55
  • I think your call on the transpiler is probably where it's at. Will keep investigating and report back if I find anything :) – almostflan Commented Sep 16, 2015 at 21:56
  • 1 Anyway, I'm going to stop investigating. I like the workaround provided here. stackoverflow./a/31789308/1438285 – almostflan Commented Sep 16, 2015 at 22:39
 |  Show 6 more ments

1 Answer 1

Reset to default 9

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.

本文标签: javascriptWhy do immutablejs classes not require quotnewquotStack Overflow