默认情况
//如果指定的返回值是基本数据类型的话,仍然会返回新对象实例。
function A(){
this.x=3;
return "OK";
}
var a = new A();
a instanceof A === true;
"x" in a === true
//如果指定返回对象了的话,被返回的对象就成了指定的对象值。在这种情况下,this值所引用的对象就被丢弃了。
function B(){
this.x=3;
return Object("OK");
}
var b = new B();
"x" in b === false
b instanceof B === false
b instanceof String === true
更直观的例子:
function User( name, age){
this.name = name;
this.age = age;
// return; // 返回 this
// return null; // 返回 this
// return this;
// return []; // 返回 []
// return function(){}; // 返回 这个 function,抛弃 this
// return false; // 返回 this
// return new Boolean( false); // 返回新 boolean;抛弃 this
// return 'hello world'; // 返回 this
// return new String( 'hello world'); // 返回 新建的 string,抛弃 this
// return 2; // 返回 this
// return new Number( 32); // 返回新的 number,抛弃 this
}
即返回值为简单的基本数据类型,而不是一个显示的对象(包括基本类型的对象)的话,那么返回值仍然为新创建的对象。
//如果指定的返回值是基本数据类型的话,仍然会返回新对象实例。
function A(){
this.x=3;
return "OK";
}
var a = new A();
a instanceof A === true;
"x" in a === true
//如果指定返回对象了的话,被返回的对象就成了指定的对象值。在这种情况下,this值所引用的对象就被丢弃了。
function B(){
this.x=3;
return Object("OK");
}
var b = new B();
"x" in b === false
b instanceof B === false
b instanceof String === true
更直观的例子:
function User( name, age){
this.name = name;
this.age = age;
// return; // 返回 this
// return null; // 返回 this
// return this;
// return []; // 返回 []
// return function(){}; // 返回 这个 function,抛弃 this
// return false; // 返回 this
// return new Boolean( false); // 返回新 boolean;抛弃 this
// return 'hello world'; // 返回 this
// return new String( 'hello world'); // 返回 新建的 string,抛弃 this
// return 2; // 返回 this
// return new Number( 32); // 返回新的 number,抛弃 this
}
即返回值为简单的基本数据类型,而不是一个显示的对象(包括基本类型的对象)的话,那么返回值仍然为新创建的对象。