Immutable.js如何省略new关键字?

How does Immutable.js omit the new keyword?

所以,一个 ES6 语法难题。据我所知,如果你创建一个 javascript class 例如:DragonSlayer 然后创建一个 class 的实例你需要使用 'new' 关键字。

let girl = new DragonSlayer();

如果您不想使用 'new' 关键字,您可以创建一个包装函数。

function ADragonSlayer () {
    return new DragonSlayer() }

let girl = ADragonSlayer();

谁能给我解释一下 Immutable.js 库是如何工作的?

这似乎创建了一个名为 List 的 class,然后将具有该 class 的对象导出为同名的 属性(您在导入期间通过解构获得)。然而,要创建一个实例,您可以只调用函数而根本没有新的。

const { List } = require('immutable')

let newList = List();

我已经在源代码中四处寻找,但到目前为止还无法掌握这种黑魔法是如何构建的。有人有一些指示吗?

你说得对 classes 不能在没有 new 的情况下被实例化:

class List {}; List()
// TypeError: class constructors must be invoked with |new|

但是您可能 require compiled version of immutable.js,其中 class 声明被编译为:

var List = (function (IndexedCollection$) {
  function List(value) {
    // ...
   return empty.withMutations(function (list) {
  }
  // ...
  return List;
}(...))

...可以在没有 new.

的情况下调用

它利用了Object.create

constructor 你会看到它会 return 返回:

  1. 传递的值
  2. empty 是 return 从 emptyList() which calls makeList()
  3. 编辑的值
  4. 或者直接从 makeList() 调用中 return 得到的值。

在 makeList() 内部是对 Object.create() 的调用,它根据传递的原型创建一个新对象

https://github.com/facebook/immutable-js/blob/d960d5c4e00f616aa2aec0ecd765735525c6166f/src/List.js#L407

const list = Object.create(ListPrototype);

这就是您调用 List()

时 return 编辑的最终结果

还有一个问题here问的是Object.create而不是new的使用。