new Fn() 與 Fn() 的區別在於:new 創建實例並綁定 this,但若構造函數**顯式返回對象**(含函數、數組、對象),則返回該對象而非實例。
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 屬性)
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() 統一返回對象。class 語法禁止顯式返回非 this 對象,避免此類困惑。