默认情况下,没有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里的内容,自己做了一点整理,以便以后自己回顾。