在 javascript 中,new 运算符是否总是 return new 语句中提到的相同类型的对象?

In javascript, does the new operator always return an object of same type which is mentioned in the new statement?

鉴于此代码:

function foo(){ 
   return foo; 
}
var bar = new foo();

console.log(bar instanceof foo);

我希望输出为 "true"。然而,却是"false".

为什么 bar 对象不是 foo 类型?

另一方面,如果我只是 return 来自 foo 的数字(比如 2),我得到的输出为 true。

当您 return 来自构造函数的基元(比如 2)时,return 值将被忽略。由 new 创建的对象改为 returned,就像构造函数没有 return 语句一样。如果您 return 来自构造函数的对象,则该对象是 returned(注意:函数是 Javascript 中的对象),无论该对象是否具有构造函数作为其内部原型。

在你的例子中,你return正在执行一个函数;该函数是 foo,但它不是 foo 的实例。

See new operator