js new 與 return


前置:

  默認情況下, 函數的返回值是 undefined (即沒有定義返回值)。

 

new 操作符

  js 中的 new 操作符,可以是我們像 java 一樣,獲得一個新的對象,例如:

function Person() {
  this.heart = 'red';
}

let per = new Person();
console.log(per.heart);  // red

   那么,在 new 的時候,內部發生了什么呢?

  我們用偽代碼模擬一下:

new Person() = {
  var obj = {};
  obj.__proto__ = Person.prototype;
  var result = Person.call(obj);
  return typeof result === 'object' ? result : obj;
}
  1. 創建一個空對象 obj;
  2. 設置 obj 的原型鏈:obj -> Person.prototype -> Object.prototype -> null;
  3. 在 obj 的執行環境中調用(執行) Person 函數;(或者說改變 this 的指向)
  4. 考察第三步的返回值,無返回值或者返回一個非對象值,則將 obj 返回作為新的對象,否則將返回值作為新的對象返回。

 

  以上就是 new 操作符的運行機制簡略版。

 

與 return 的化學反應

  在大致理解了 new 的運行機制之后,答案就呼之欲出了:

  

  如果我們的構造函數 return 的是簡單的基本數據類型(undefinded、數字、字符串、布爾),依舊能夠正確 new 出想要的對象;

  如果構造函數 return 的是對象(包括基本數據類型的包裝對象,如:Object('OK') 等),那么我們 new 的時候就得不到想的對象;

 

  下面貼一個實例:

// 示例引自:https://www.jianshu.com/p/ed692646ee7c
function User( name, age){
  this.name = name;
  this.age = age;

// return;                              // 返回 this
// return null;                         // 返回 this
// return this;                         // 返回 this
// return false;                        // 返回 this
// return 'hello world';                // 返回 this
// return 2;                            // 返回 this

// return [];                            // 返回 新建的 [], user.name = undefined
// return function(){};                  // 返回 新建的 function,拋棄 this, user.name = undefined
// return new Boolean( false);           // 返回 新建的 boolean,拋棄 this, user.name = undefined
// return new String( 'hello world');    // 返回 新建的 string,拋棄 this, user.name = undefined
// return new Number( 32);               // 返回 新的 number,拋棄 this, user.name = undefined
}
var user = new User("小白",20)
console.log(user);


免責聲明!

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



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