JS中new操作符与函数返回值return

默认情况



       默认情况下函数的返回值为undefined(即没有显示地定义返回值的话),但是构造函数比较例外,new构造函数在没有return的情况下默认返回新创建的对象。但是在有显示返回值的情况下,如果返回值为基本数据类型的话(stringnumberbooleanundefinednull),返回值仍然为新创建的对象,这一点比较奇怪,需要注意。只有在显示返回一个非基本数据类型的对象的时候,函数的返回值才为指定的对象。在这种情况下,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
}

即返回值为简单的基本数据类型,而不是一个显示的对象(包括基本类型的对象)的话,那么返回值仍然为新创建的对象。

       默认情况下函数的返回值为undefined(即没有显示地定义返回值的话),但是构造函数比较例外,new构造函数在没有return的情况下默认返回新创建的对象。但是在有显示返回值的情况下,如果返回值为基本数据类型的话(stringnumberbooleanundefinednull),返回值仍然为新创建的对象,这一点比较奇怪,需要注意。只有在显示返回一个非基本数据类型的对象的时候,函数的返回值才为指定的对象。在这种情况下,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
}

即返回值为简单的基本数据类型,而不是一个显示的对象(包括基本类型的对象)的话,那么返回值仍然为新创建的对象。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值