我对 JavaScript 中的 new 关键字有点困惑。举个例子
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 }
我希望能够创建一个新的“A”实例而不必使用“new”。为此,我有“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
做的不是“正常”的(没有理由这样做) B
显式返回的值也由new B
返回
如果您坚持正常使用 new
,您就不会感到困惑:向它传递一个普通的构造函数,这是一个不返回任何内容而只是简单地初始化其上下文的函数(这个
)。
关于javascript - 新函数返回新函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31588874/