首页 > Web开发 > 详细

js 构造函数中的 return

时间:2019-09-01 13:00:24      阅读:68      评论:0      收藏:0      [点我收藏+]

本文链接:https://blog.csdn.net/qq_36209248/article/details/89190978


默认情况下,没有return的函数的返回值为undefined(即没有定义返回值),如果定义了return,则返回指定对象。
但是构造函数比较t特殊,new构造函数在没有return的情况下默认返回新创建的对象。在有return的情况下,需要分为两个情况考虑:

如果返回值为基本数据类型(string,number,boolean,undefined,null),那么返回值为新建对象实例,即this。
var a = function S(){
  this.x=3;
  return 1;
}
var b = new a();
console.log(a); //{x:3}

如果返回值为一个非基本数据类型的对象,函数的返回值为指定的对象,this值所引用的对象被丢弃。
var a = function S(){
  this.x=3;
  return a;
}
var b = new a();
console.log(b); //S(){this.x=3;return a }

直观的例子:

var a = function User( name, age){
  this.name = name;
  this.age = age;

  // return; // 返回 this
  // return null; // 返回 this
  // return this; // 返回 this
  // return true; // 返回 this
  // return ‘string‘; // 返回 this
  // return 1; // 返回 this
  // 以上都返回{name:"哈哈",age:18}
  // return []; // 返回 新建的 []
  // return function(){}; // 返回 新建的 function,抛弃 this
  // return new Boolean( false); // 返回 新建的 boolean,抛弃 this
  // return new String( ‘hello world‘); // 返回 新建的 string,抛弃 this
  // return new Number( 32); // 返回新的 number,抛弃 this
}
var b=new a("哈哈",18)
console.log(b);

主要是JS——new与return里的内容,自己做了一点整理,以便以后自己回顾。
————————————————
版权声明:本文为CSDN博主「还缺个男朋友」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_36209248/article/details/89190978

js 构造函数中的 return

原文:https://www.cnblogs.com/jeff-zhu/p/11441599.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!