【发布时间】:2011-02-25 16:56:42
【问题描述】:
当 JavaScript 函数体中的 return 语句用作新对象的构造函数时(带有 'new' 关键字)有什么作用?
【问题讨论】:
标签: javascript constructor return
当 JavaScript 函数体中的 return 语句用作新对象的构造函数时(带有 'new' 关键字)有什么作用?
【问题讨论】:
标签: javascript constructor return
通常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。
【讨论】:
使用new操作符的原因是为了确保构造函数内部的this引用一个new上下文,它支持:
this.functionName = function(){...};
,并允许使用instanceof 运算符:
function foo() {...}
var bar = new foo();
alert(bar instanceof foo);
在这样的构造函数中使用return {...} 会否定这两种效果,因为这样的模式不需要this,而instanceof 将返回false。
【讨论】: