紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS new 運算子:用法、建構函式與回傳值

JS new 運算子:用法、建構函式與回傳值 特色圖片

JS new 運算子(new operator)用來呼叫建構函式(constructor,樂詞網譯為「建構子」),建立一個物件實例(instance)。依 MDN 的說明,它可以建立自訂型別的物件,也可以建立有建構函式的內建型別物件。

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

const car1 = new Car("Eagle", "Talon TSi", 1993);

console.log(car1.make);   // Eagle
console.log(car1);        // Car { make: 'Eagle', model: 'Talon TSi', year: 1993 }

new Car(...) 回傳的是新建立的 car1。沒有 new 直接呼叫 Car(...) 的話,就不會建立新物件,this 的值也不同(this 的規則請參考 this 的語法文)。

new 依序做了什麼

依 MDN 的說明,new 執行時依序做四件事:

  1. 建立一個空的普通物件,下面稱為 newInstance。
  2. 把 newInstance 的原型([[Prototype]])指向建構函式的 prototype 屬性;如果 prototype 不是物件,newInstance 的原型就維持 Object.prototype。
  3. 以給定的引數執行建構函式,並把 newInstance 當作 this。
  4. 處理回傳值:建構函式回傳物件時,那個物件就是 new 運算式的結果;沒有回傳,或回傳原始值時,結果是 newInstance。

用剛才的 Car 可以看到第 2 步的結果:實例的原型就是 Car.prototype。

console.log(Object.getPrototypeOf(car1) === Car.prototype);   // true
console.log(car1 instanceof Car);                             // true

instanceof 運算子的用法,請參考 instanceof 的語法文。

自訂建構函式

定義自訂型別分兩步:先寫一個建構函式,用 this 替新物件加上屬性;再用 new 建立實例。每次呼叫 new 都會得到各自獨立的物件:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

const myCar = new Car("Eagle", "Talon TSi", 1993);
const kensCar = new Car("Nissan", "300ZX", 1992);

console.log(myCar.make, myCar.year);   // Eagle 1993
console.log(kensCar.make);             // Nissan

物件的屬性也可以是另一個物件。下面的 Car 多了 owner 屬性,放的是用 Person 建立的物件:

function Person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
}

function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
}

const rand = new Person("Rand McNally", 33, "M");
const ken = new Person("Ken Jones", 39, "M");

const car1 = new Car("Eagle", "Talon TSi", 1993, rand);
const car2 = new Car("Nissan", "300ZX", 1992, ken);

console.log(car2.owner.name);   // Ken Jones

建構函式的回傳值

建構函式通常不寫 return。依 MDN 說明,建構函式可以回傳值來改寫一般的建立過程,結果取決於回傳的是不是物件:

建構函式的回傳new 運算式的結果
沒有回傳newInstance(也就是 this)
回傳原始值(例如數字)newInstance
回傳物件(包含陣列、函式)回傳的那個物件
function R1() { this.a = 1; return { a: 2 }; }
function R2() { this.a = 1; return 42; }
function R3() { this.a = 1; }
function R4() { this.a = 1; return [10]; }

console.log(new R1().a);   // 2
console.log(new R2().a);   // 1
console.log(new R3().a);   // 1
console.log(new R4());     // [ 10 ]

R2 回傳 42 是原始值,被忽略,結果仍是 this;R1 與 R4 回傳物件,結果就是那個物件,所以 new R1() 不是 R1 的實例:

console.log(new R2() instanceof R2);   // true
console.log(new R1() instanceof R1);   // false

原型與實例

加在建構函式 prototype 上的屬性,所有用它建立的實例都讀得到;實例自己有同名屬性時,會優先使用實例自己的:

function Car() {}
const car1 = new Car();
const car2 = new Car();

console.log(car1.color);   // undefined

Car.prototype.color = "original color";
console.log(car1.color);   // original color

car1.color = "black";
console.log(car1.color);                          // black
console.log(Object.getPrototypeOf(car1).color);   // original color
console.log(car2.color);                          // original color

car1 自己加上 color 之後,只有它自己讀到 black,原型上的值和 car2 都沒有變。

括號與優先順序

沒有引數時,括號可以省略,new Foo 等同 new Foo():

function Foo() {
  this.a = 1;
}

console.log(JSON.stringify(new Foo));     // {"a":1}
console.log(JSON.stringify(new Foo()));   // {"a":1}

new 後面接的建構函式部分,有一些寫法的限制:

  • 可選串連(?.)不能直接寫在 new 後面:new x?.y() 是語法錯誤,要用括號包起來寫成 new (x?.y)()。
  • 函式呼叫的結果當建構函式要加括號:new x()() 會被解析成 (new x())(),想用 x() 的回傳值當建構函式,要寫成 new (x())()。
try {
  new Function("const x = { y: function () {} }; new x?.y();");
} catch (e) {
  console.log(e.name);   // SyntaxError
}

const x = {
  y: function Y() {
    this.k = 1;
  },
};
console.log(new (x?.y)());   // Y { k: 1 }

function Maker() {
  return function Inner() {
    this.v = 1;
  };
}
console.log(new (Maker())());   // Inner { v: 1 }

SyntaxError 的錯誤訊息文字依引擎而異;Node.js v22.20.0 的訊息是 Invalid optional chain from new expression。

搭配 class 使用

class 只能用 new 建立實例,沒有 new 直接呼叫 class 會丟出 TypeError:

class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const p = new Person("Caroline");
p.greet();   // Hello, my name is Caroline

try {
  Person("x");
} catch (e) {
  console.log(e.name, "|", e.message);
}
// TypeError | Class constructor Person cannot be invoked without 'new'

錯誤訊息的文字依引擎而異,上面是 Node.js v22.20.0 的輸出。class 本身的完整用法,可前往 class 的語法文觀看。

new.target:判斷有沒有用 new 呼叫

new.target 是專門給函式內部用的語法:用 new 呼叫時,它是被 new 呼叫的那個函式或 class;沒有用 new 呼叫(一般的函式呼叫)時,它是 undefined。

function Car(color) {
  if (!new.target) {
    // 當成一般函式呼叫
    return `${color} car`;
  }
  // 用 new 呼叫
  this.color = color;
}

console.log(Car("red"));       // red car
console.log(new Car("red"));   // Car { color: 'red' }

也可以反過來,沒有用 new 就直接丟出錯誤:

function Foo() {
  if (!new.target) {
    throw new TypeError("calling Foo constructor without new is invalid");
  }
}

try {
  Foo();
} catch (e) {
  console.log(String(e));
  // TypeError: calling Foo constructor without new is invalid
}

在 class 的建構函式裡,new.target 是 new 實際呼叫的那個 class,即使程式碼在父類別的建構函式裡也一樣:

class A {
  constructor() {
    console.log(new.target.name);
  }
}

class B extends A {
  constructor() {
    super();
  }
}

new A();   // A
new B();   // B

new.target 的其他規則,依 MDN 整理如下:

  • 它是「meta-property」(new、.、target 三者組成的特殊運算式),不是對 new 取屬性。
  • 用 Reflect.construct() 呼叫時,new.target 是傳入的 newTarget 參數(預設為 target)。
  • 箭頭函式沒有自己的 new.target,沿用外層的;如果外層不是函式或 class,會是語法錯誤。
  • 在函式或 class 以外使用 new.target 是語法錯誤;靜態初始化區塊裡是 undefined。

內建物件有的要用 new、有的不能用

MDN 把內建物件分成幾類:

類型內建物件有沒有 new 的差別
兩種呼叫結果相同Array()、Error()、Function()沒有差別
回傳型別不同Boolean()、Number()、String()不用 new 是轉成原始值,用 new 是包裝物件
回傳型別不同Date()不用 new 回傳表示現在時間的字串,用 new 回傳 Date 物件
只能不用 newSymbol()、BigInt()用 new 會丟出 TypeError
只能用 newMap、Proxy不用 new 會丟出 TypeError
console.log(typeof Number("5"), typeof new Number("5"));     // number object
console.log(typeof String(1), typeof new String(1));         // string object
console.log(typeof Date(), typeof new Date());               // string object

try {
  new Symbol();
} catch (e) {
  console.log(e.name, "|", e.message);   // TypeError | Symbol is not a constructor
}

try {
  Map();
} catch (e) {
  console.log(e.name, "|", e.message);   // TypeError | Constructor Map requires 'new'
}

錯誤訊息的文字依引擎而異,上面是 Node.js v22.20.0 的輸出。

常見錯誤:x is not a constructor

用 new 呼叫不是建構函式的值,會丟出 TypeError: x is not a constructor。MDN 列出的例子:

for (const run of [
  () => { const Car = 1; new Car(); },
  () => { new Math(); },
  () => { function* f() {} const obj = new f(); },
]) {
  try {
    run();
  } catch (e) {
    console.log(e.name, "|", e.message);
  }
}
// TypeError | Car is not a constructor
// TypeError | Math is not a constructor
// TypeError | f is not a constructor

Math、JSON、Symbol、Reflect、Intl、Atomics 這些內建物件的屬性與方法都是靜態的,不能當建構函式;產生器函式(function*)也不能當建構函式。

建立 Object 實例的 new Object(),另有專文說明,可前往 Object 建構函式的語法文觀看。

注意事項

  1. 沒有引數時可以省略括號:new Foo 等同 new Foo(),但 new x?.y() 是語法錯誤,要寫成 new (x?.y)()。
  2. 建構函式回傳物件會取代 this:回傳原始值則被忽略。
  3. class 一定要用 new:沒有 new 會丟出 TypeError。
  4. 一般的建構函式忘了 new 不會自己報錯:可以在函式開頭用 new.target 判斷。
  5. Symbol()、BigInt() 不能用 new,Map、Proxy 一定要用 new:其他內建物件各有不同的行為。
  6. new.target 只能寫在函式或 class 裡:外層沒有函式的箭頭函式也不行。
  7. 加在 prototype 的屬性所有實例共用:實例自己設定同名屬性只影響它自己。

支援版本

依 MDN 瀏覽器相容性資料(browser-compat-data 8.1.10,查詢日期 2026-11-24):

環境new 運算子new.target
Chrome146
Edge1213
Firefox141
Safari111
Node.js0.10.05.0.0

Deno 從 1.0 開始支援兩者。Internet Explorer 3 起支援 new 運算子。MDN 把 new 標為 Baseline Widely available(2015 年 7 月起各主流瀏覽器都支援),new.target 則是自 2017 年 9 月起。

補充說明:範例在 Node.js v22.20.0 執行;多數範例來自 MDN 的 new、new.target 與「is not a constructor」頁面,回傳值、括號寫法與內建物件的範例是依 MDN 說明另外撰寫的示範。

參考資料與延伸閱讀

發佈留言