【问题标题】:Return Statement in JS ConstructorsJS 构造函数中的返回语句
【发布时间】:2011-02-25 16:56:42
【问题描述】:

当 JavaScript 函数体中的 return 语句用作新对象的构造函数时(带有 'new' 关键字)有什么作用?

【问题讨论】:

标签: javascript constructor return


【解决方案1】:

通常return 只是退出构造函数。但是,如果返回值为 Object,则将其用作 new 表达式的值。

考虑:

function f() {
   this.x = 1;
   return;
}
alert((new f()).x);

显示 1,但是

function f() {
   this.x = 1;
   return { x: 2};
}
alert((new f()).x);

显示 2。

【讨论】:

  • 谢谢,这正是我想知道的。
【解决方案2】:

使用new操作符的原因是为了确保构造函数内部的this引用一个new上下文,它支持:

this.functionName = function(){...};

,并允许使用instanceof 运算符:

function foo() {...}
var bar = new foo();
alert(bar instanceof foo);

在这样的构造函数中使用return {...} 会否定这两种效果,因为这样的模式不需要this,而instanceof 将返回false

【讨论】:

  • 感谢您的回复,我认为这揭示了 js 构造函数的一个缺点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
相关资源
最近更新 更多