構造函數用return 會出顯什么情況


首先我們都知道js中構造函數一般應該是這樣的

  1. function Super (a) {  
  2.    this.a = a;  
  3. }  
  4. Super.prototype.sayHello = function() {  
  5.    alert('hello world');  
  6. }  

但如果在構造函數中 加入 return 會是什么結果呢

 

  1. function Super (a) {  
  2.    this.a = a;  
  3.   
  4.    return {a: 2};  
  5. }  
  6. Super.prototype.sayHello = function() {  
  7.    alert('hello world');  
  8. }  



new 這個構造函數會返回什么? 

 

Object {a: 2}

為什么會這樣?我們的構造函數和原型上的方法呢?別急 我們再來 列出集中情況

  1. //直接 return  
  2. function A(){  
  3.    return;  
  4. }  
  5. //返回 數字類型  
  6. function B(){  
  7.    return 123;  
  8. }  
  9. //返回 string類型  
  10. function C(){  
  11.    return "abcdef";  
  12. }  
  13. //返回 數組  
  14. function D(){  
  15.    return ["aaa", "bbb"];  
  16. }  
  17. //返回 對象  
  18. function E(){  
  19.    return {a: 2};  
  20. }  
  21. //返回 包裝類型  
  22. function F(){  
  23.    return new Number(123);  
  24. }  


結果分別是

  1. A {}  
  2. B {}  
  3. C {}  
  4. ["aaa", "bbb"]  
  5. Object {a: 2}  
  6. Number {[[PrimitiveValue]]: 123}  
  7. A {}  

 

我們可以看出 return 基本類型 會返回一個空對象 

而返回對象類型 則會返回這對象

與我們常用的那個構造函數相結合

  1. function Super (a) {  
  2.    this.a = a;  
  3.    return 123;  
  4. }  
  5. Super.prototype.sayHello = function() {  
  6.    alert('hello world');  
  7. }  
  8. function Super_ (a) {  
  9.    this.a = a;  
  10.    return {a: 2};  
  11. }  
  12. Super_.prototype.sayHello = function() {  
  13.    alert('hello world');  
  14. }  

 

分別new Super(1); new Super_(1);

結果是

Super {a: 1} 具有原型方法sayHello

Object {a: 2}

 

好了現在我們總結下 在構造函數中 return 基本類型 不會影響

構造函數的值而 return 對象類型 則會替代構造函數返回該對象


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM