本文鏈接: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