新函数返回新函数

New function returning new function

我对 JavaScript 中的新关键字有点困惑。举个例子

function A (value) {
    this.a = value;
}

function B (value) {
    return new A (value);
}

console.log (    B (0)); // { a: 0 }
console.log (new B (0)); // { a: 0 }

我希望能够在不使用 "new" 的情况下创建 "A" 的新实例。为此,我有 "B()",但是,当我调用 "new B()" 时,它似乎做与 "B()" 相同的事情,就好像 "new" 被忽略了一样。在这两种情况下,instanceof 都等于 "A"。究竟是怎么回事?

来自the MDN on new

The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

此摘录向您展示了

  • 你用 new B 做的不是 "normal"(没有理由这样做)
  • B 明确 return 的值也由 new B
  • return 编辑

如果你坚持 new 的正常使用,你就不会感到困惑:传递给它一个普通的构造函数,这是一个 return 除了简单地初始化它的上下文之外的函数(this).