new Fn() 與 Fn() 乍看相似,實則觸發完全不同的執行機制。本文從執行上下文、this 綁定、回傳值行為、全域汙染風險四個維度深度剖析兩者本質差異,並提供防禦性編程模式。
function Me(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
var me1 = new Me('Fei', 20, 'IT'); // 構造函式調用
var me2 = Me('Fei', 20, 'IT'); // 普通函式調用
console.log(me1); // Me { name: 'Fei', age: 20, job: 'IT' }
console.log(me2); // undefined
console.log(window.name); // 'Fei' (非嚴格模式汙染全域!)
console.log(window.age); // 20
console.log(window.job); // 'IT'
this 綁定| 調用方式 | 執行上下文 | this 指向 |
|---|---|---|
new Fn() | 新建立的空物件上下文 | 指向該新物件 (實例) |
Fn() | 當前呼叫上下文 (全域/物件方法) | 非嚴格模式: window/global;嚴格模式: undefined |
new 實質上創建一個「乾淨的上下文沙箱」,隔離構造邏輯與外部環境。
new Fn():預設回傳 this (新實例);若構造函式顯式 return 非原始值物件,則回傳該物件 (原實例被丟棄)。Fn():回傳構造函式 return 的值;無 return 則回傳 undefined。function A() { return { custom: true }; }
console.log(new A()); // { custom: true } (實例被替換)
console.log(A()); // { custom: true }
function B() { return 42; }
console.log(new B()); // B {} (忽略原始值回傳,仍回傳實例)
console.log(B()); // 42
直接呼叫構造函式等同於:
// 等價於
window.name = 'Fei';
window.age = 20;
window.job = 'IT';
return undefined;
嚴格模式 ('use strict') 下會拋出 TypeError: Cannot set property 'name' of undefined,及早暴露錯誤。
instanceof 驗證me1 instanceof Me; // true
me2 instanceof Me; // false (me2 是 undefined)
User、Order、XMLHttpRequest** — 明確告知呼叫者「請使用 new」。getUser、formatDate。new-cap 規則檢測依據。function User(name) {
if (!(this instanceof User)) {
return new User(name); // 自動補 new
}
this.name = name;
}
console.log(User('Alice').name); // 'Alice' (自動修正)
console.log(new User('Bob').name); // 'Bob'
'use strict';
function User(name) {
if (!new.target) {
throw new TypeError('Constructor User must be called with new');
}
this.name = name;
}
// User('Alice'); // TypeError
// new User('Bob'); // OK
new.target 在構造函式內指向被 new 調用的構造函式,普通呼叫為 undefined。
function createUser(name) {
return { name: name, greet: function() { console.log('Hi ' + this.name); } };
}
var u = createUser('Alice'); // 無需 new,語意清晰
| 特性 | new Fn() | Fn() |
|---|---|---|
| 建立新物件 | ✅ 自動 | ❌ 否 |
this 指向 | 新物件 | 全域/undefined |
| 原型鏈連接 | ✅ obj.__proto__ === Fn.prototype | ❌ |
| 預設回傳 | 新物件 | undefined |
instanceof Fn | true | false |
| 全域汙染風險 | 無 | 高 (非嚴格模式) |
鐵律:定義構造函式時首字母大寫、文檔標註 @constructor、內部加入 new.target 守衛;呼叫端務必加 new。若 API 設計不想暴露 new,請提供工廠函式 createXxx()。