首頁  >  文章  >  web前端  >  ES6 中可以呼叫沒有「new」的類別建構子嗎?

ES6 中可以呼叫沒有「new」的類別建構子嗎?

Susan Sarandon
Susan Sarandon原創
2024-10-26 01:55:02296瀏覽

 Can You Call a Class Constructor Without 'new' in ES6?

ES6 中沒有new 關鍵字呼叫類別建構子

給定類別定義:

class Foo {
  constructor(x) {
    if (!(this instanceof Foo)) return new Foo(x);
    this.x = x;
  }
  hello() {
    return `hello ${this.x}`;
  }
}

這是不可能的不使用new 關鍵字直接呼叫類別建構子。這是因為 ES6 中的類別本質上有一個建構函數,該函數在呼叫該類別時會被呼叫。

調用沒有new 的類別會導致錯誤:

Cannot call a class as a function

此錯誤訊息清楚地表明類別建構子只能使用new 運算子調用,這是建立類別的新實例所必需的。

要克服此限制,請考慮以下方法:

  • 使用常規函數:
function Foo(x) {
  this.x = x;
  this.hello = function() {
    return `hello ${this.x}`;
  }
}
  • 總是使用new 呼叫類別:
(new Foo("world")).hello(); // "hello world"
  • 將類別包裝在函數中並使用new 呼叫:
var FooWrapper = function(...args) { return new Foo(...args) };
FooWrapper("world").hello(); // "hello world"

以上是ES6 中可以呼叫沒有「new」的類別建構子嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn