一、new.target的基礎知識
new.target是一個特殊的meta屬性,它指向調用構造函數的構造器函數。如果在非構造函數中使用,它將是undefined.
class Foo { constructor() { console.log(new.target === Foo); // true } } new Foo();
上面的代碼中,new.target指向被調用的構造函數,因此在構造函數內部使用new.target得到的就是構造函數本身。
二、new.target的應用場景
new.target可用於實現多態。
class Shape { constructor() { console.log(new.target); } } class Rectangle extends Shape { constructor() { super(); } } class Circle extends Shape { constructor() { super(); } } new Rectangle(); // 輸出Rectangle new Circle(); // 輸出Circle
上面的代碼中,當實例化Rectangle和Circle時都調用了Shape的構造函數,但是通過使用new.target可以獲取到實例化對象的構造函數從而實現多態。
此外,new.target也可以用於檢測構造函數的可用性。
function Foo() { if (!new.target) { throw 'Foo()必須使用new運算符調用!'; } console.log('foo'); } new Foo(); // 輸出foo Foo(); // 拋出錯誤
上面的代碼中,如果Foo()沒有使用new運算符調用,將會拋出錯誤。
三、總結
new.target是ES6引入的一個特殊的meta屬性,用於指向調用構造函數的構造器函數。它可以用於實現多態,檢測構造函數的可用性等。在實際開發中,合理使用new.target可以提高代碼的可讀性,減少一些錯誤發生的可能性。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/297762.html