萬盛學電腦網

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

JavaScript new 運算子與直接呼叫函式的關鍵差異:執行上下文與 this 綁定深度解析

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'

核心差異深度解析

1. 執行上下文與 this 綁定

調用方式執行上下文this 指向
new Fn()新建立的空物件上下文指向該新物件 (實例)
Fn()當前呼叫上下文 (全域/物件方法)非嚴格模式: window/global;嚴格模式: undefined

new 實質上創建一個「乾淨的上下文沙箱」,隔離構造邏輯與外部環境。

2. 回傳值行為差異

  • 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

3. 全域汙染風險 (非嚴格模式)

直接呼叫構造函式等同於:

// 等價於
window.name = 'Fei';
window.age = 20;
window.job = 'IT';
return undefined;

嚴格模式 ('use strict') 下會拋出 TypeError: Cannot set property 'name' of undefined,及早暴露錯誤。

4. instanceof 驗證

me1 instanceof Me; // true
me2 instanceof Me; // false (me2 是 undefined)

構造函式命名慣例

  • **PascalCase** (首字母大寫):**User、Order、XMLHttpRequest** — 明確告知呼叫者「請使用 new」。
  • 普通函式用 **camelCase**:getUser、formatDate。
  • 此慣例為 ESLint new-cap 規則檢測依據。

防禦性編程:確保構造函式被正確調用

模式一:instanceof 守衛 (支援無 new 呼叫自動修正)

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'

模式二:嚴格模式 + new.target (ES6)

'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。

模式三:工廠函式完全避開 new

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 Fntruefalse
全域汙染風險無高 (非嚴格模式)

鐵律:定義構造函式時首字母大寫、文檔標註 @constructor、內部加入 new.target 守衛;呼叫端務必加 new。若 API 設計不想暴露 new,請提供工廠函式 createXxx()。

copyright © 萬盛學電腦網 all rights reserved