如果构造函数返回新的Func()会发生什么

时间:2015-10-13 00:42:05

标签: javascript prototype

写作时

*

然而,当我这样做时

function abc() {
 return 3;
}

var t = new abc();
console.log(t); // abc {}

所以在第一个例子中,为什么它在返回实际返回数字时返回一个对象。当我返回新的Func()....我得到新的Obj ..返回值。

在一个场景中,我得到了返回值,在其他主要对象中。

2 个答案:

答案 0 :(得分:1)

这符合ES5.1规范13.2.2 [[Construct]]

相关部分:

  
      
  1. 让结果成为调用[[Call]]内部属性的结果   F,提供obj作为此值并提供参数列表   作为args传递给[[Construct]]。
  2.   
  3. 如果Type(result)是Object,则返回结果。
  4.   
  5. 返回obj。
  6.   

ES2015的类似部分:9.2.2 [[Construct]] ( argumentsList, newTarget)

  
      
  1. 让结果为OrdinaryCallEvaluateBody(F,argumentsList)。
  2.   
  3. 从执行上下文堆栈中删除并恢复   callerContext作为正在运行的执行上下文。
  4.   
  5. 如果结果。[[type]]返回,那么      
        
    • 如果Type(result。[[value]])是Object,则返回NormalCompletion(result。[[value]])。
    •   
    • 如果kind是“base”,则返回NormalCompletion(thisArgument)。
    •   
    • 如果结果。[[value]]未定义,则抛出TypeError异常。
    •   
  6.   

感谢@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