例如,这是非常好的代码。 (风格为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
最佳答案
看起来 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
调用。
关于javascript - 为什么 immutable.js 类不需要 "new"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32619382/