萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript new Function() vs 直接調用:返回值差異深度解析

new Fn() 與 Fn() 的區別在於:new 創建實例並綁定 this,但若構造函數**顯式返回對象**(含函數、數組、對象),則返回該對象而非實例。

案例 1:返回函數(引用類型)

function Test(){
    this.name = 'Test';
    return function(){ return true; }; // 返回函數對象
}

const a = new Test(); // a 是返回的函數,而非 Test 實例
const b = Test();     // b 也是同一個函數
console.log(a === b); // true
console.log(a.name);  // undefined(函數無 name 屬性)

案例 2:返回基本類型

function Test(){
    this.name = 'Test';
    return 'Test'; // 返回字符串
}

const a = Test();      // "Test"
const b = new Test();  // Test { name: 'Test' } 實例
console.log(typeof a, typeof b); // "string" "object"

規則總結

構造函數返回new Fn() 結果Fn() 結果
無 return / return this / 返回基本類型新實例 (this)undefined / 基本值
返回對象(Object/Array/Function/Date/RegExp...)**返回該對象**(忽略 this)返回該對象

實戰啟示

  • 工廠函數常利用此特性:function create() { return {method(){}} } 可直接 new create() 或 create() 統一返回對象。
  • 構造函數**不要**顯式返回對象,除非刻意實現單例/工廠模式。
  • ES6 class 語法禁止顯式返回非 this 對象,避免此類困惑。
copyright © 萬盛學電腦網 all rights reserved