Ton*_*ony 9 javascript constructor return
当JavaScript函数用作新对象的构造函数(带有'new'关键字)时,返回语句在JavaScript函数体中的作用是什么?
Amn*_*non 22
通常return只是退出构造函数.但是,如果返回的值是Object,则将其用作new表达式的值.
考虑:
function f() {
this.x = 1;
return;
}
alert((new f()).x);
Run Code Online (Sandbox Code Playgroud)
显示1,但是
function f() {
this.x = 1;
return { x: 2};
}
alert((new f()).x);
Run Code Online (Sandbox Code Playgroud)
显示2.