
英文 | https://www.javascripttutorial.net在今天的文章中,我們將一起來學習 JavaScript new.target 元屬性,它該屬性會檢測是否使用了new 運算符調用了函數或構造函數。ES6 提供了一個名為 new.target 的元屬性,它允許你檢測是否使用了new 運算符調用了函數或構造函數。new.target 由 new 關鍵字、一個點和 target 屬性組成。new.target 在所有函數中都可用。但是,在箭頭函數中,new.target 是屬於周圍函數的那個。new.target 對於在運行時檢查函數是作為函數還是作為構造函數執行非常有用。在父類中確定使用 new 運算符調用的特定派生類也很方便。函數中的 JavaScript new.targetfunction Person(name) { this.name = name;}
我們可以使用 new 運算符從 Person 函數創建一個新對象,如下所示:
let john = new Person('John');console.log(john.name);//john
因為 this 設置為全局對象,即在 Web 瀏覽器中運行 JavaScript 時的 window 對象,所以 name 屬性被添加到 window 對象中,如下所示:
console.log(window.name); //Lily
為了幫助我們檢測是否使用 new 運算符調用了函數,我們可以使用 new.target 元屬性。
在常規函數調用中,new.target 返回 undefined。如果使用 new 運算符調用函數,則 new.target 返回對該函數的引用。
假設我們不希望 Person 被作為函數調用,我們可以使用 new.target 如下:
function Person(name) { if (!new.target) { throw "must use new operator with Person"; } this.name = name;}
現在,使用 Person 的唯一方法是使用 new 運算符從中實例化一個對象。如果我們嘗試將其作為常規函數調用,則會出現錯誤。
構造函數中的 JavaScript new.target
在類構造函數中,new.target 指的是由 new 運算符直接調用的構造函數。如果構造函數在父類中並且是從子類的構造函數委託的,則為 true:
class Person { constructor(name) { this.name = name; console.log(new.target.name); }}class Employee extends Person { constructor(name, title) { super(name); this.title = title; }}let john = new Person('John Doe'); // Personlet lily = new Employee('Lily Bush', 'Programmer'); // Employee
在此示例中,new.target.name 是 new.target 的構造函數引用的人性化名稱。
總結
在今天的教程中,我們學習了如何使用 JavaScript new.target 元屬性來檢測是否使用 new 運算符調用了函數或構造函數。希望今天的教程文章對你有用,如果你覺得有幫助的話,請記得點讚我,關注我,並將這篇教程文章分享給你的開發者朋友,也許對他也有用。
最後,感謝你的閱讀,編程快樂!
學習更多技能
請點擊下方公眾號

