版权声明:转载请注明出处 https://blog.csdn.net/qdmoment/article/details/82498794
有时候想写出只能被继承使用的类,这时候就要用到new.target
1含义:
new.target返回使用new方法调用类时的类的名称,子类继承父类时,new.target
会返回子类
class Rectangle {
constructor(length, width) {
console.log(new.target === Rectangle);
// ...
}
}
class Square extends Rectangle {
constructor(length) {
super(length, length);
}
}
var obj = new Square(3); // 输出 false
2,new.target的作用
------限制类的调用方法,判断new.target是不是未定义
-----写出只能被继承使用的类
class Shape {
constructor() {
if (new.target === Shape) {
throw new Error('本类不能实例化');
}
}
}
class Rectangle extends Shape {
constructor(length, width) {
super();
// ...
}
}
var x = new Shape(); // 报错
var y = new Rectangle(3, 4); // 正确