js 構造函數中的 return

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

相關文章
相關標籤/搜索