写作时
*
然而,当我这样做时
function abc() {
return 3;
}
var t = new abc();
console.log(t); // abc {}
所以在第一个例子中,为什么它在返回实际返回数字时返回一个对象。当我返回新的Func()....我得到新的Obj ..返回值。
在一个场景中,我得到了返回值,在其他主要对象中。
答案 0 :(得分:1)
这符合ES5.1规范13.2.2 [[Construct]]
相关部分:
- 让结果成为调用[[Call]]内部属性的结果 F,提供obj作为此值并提供参数列表 作为args传递给[[Construct]]。
- 如果Type(result)是Object,则返回结果。
- 返回obj。
醇>
ES2015的类似部分:9.2.2 [[Construct]] ( argumentsList, newTarget)
- 让结果为OrdinaryCallEvaluateBody(F,argumentsList)。
- 从执行上下文堆栈中删除并恢复 callerContext作为正在运行的执行上下文。
- 如果结果。[[type]]返回,那么
醇>
- 如果Type(result。[[value]])是Object,则返回NormalCompletion(result。[[value]])。
- 如果kind是“base”,则返回NormalCompletion(thisArgument)。
- 如果结果。[[value]]未定义,则抛出TypeError异常。
感谢@Barmar摘要:
换句话说,如果构造函数返回一个对象,
new
将返回该对象,否则返回this
答案 1 :(得分:1)
这个构造函数没问题:
function foo() {
// will set attribute on new object
this.age = 33;
}
t = new foo;
Object.getPrototypeOf(t); // foo
这个也是:
function bar() {
// delegates construction to other method
// object will not have prototype bar, but prototype baz
return new baz();
}
t = new bar;
Object.getPrototypeOf(t); // baz
但是这个构造函数不会像大多数人期望的那样做:
function b() {
this.age = 33;
// because you are returning a different object;
// that other object will not have its .age attribute set
// by the statements above.
// object will not have prototype b, but prototype a
return new a();
}
t = new b;
Object.getPrototypeOf(t); // a
但您可以执行以下操作:
function b() {
var o = new a();
o.age = 33;
// object will not have prototype b, but prototype a
return o;
}
t = new b;
Object.getPrototypeOf(t); // a