一、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/n/297762.html