本文连接:https://blog.csdn.net/qq_36209248/article/details/89190978函数
默认状况下,没有return的函数的返回值为undefined(即没有定义返回值),若是定义了return,则返回指定对象。
可是构造函数比较t特殊,new构造函数在没有return的状况下默认返回新建立的对象。在有return的状况下,须要分为两个状况考虑:this
若是返回值为基本数据类型(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 }
直观的例子:.net
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/89190978blog