new命令new.target属性示例
new命令
new命令是通过构造函数生成实例的命令。
new.target属性
ES6引入了new.target属性,用于确认当前作用的在哪个构造函数上。若没有通过new命令调用构造函数。
则new.target会返回undefined,否则返回当前构造函数。
示例
单个构造函数
function Animal (name) {
if (
new.target !==
undefined) {
this.name = name
}
else {
throw new Error(
'必须使用new生成实例!')
}
}
继承
class Parent{}
class Child extends Parent{
constructor(){
super()
console.log(
new.target === Child)
}
}
子类继承父类时,new.target返回当前Class — 即子类。
必须继承才能使用的类
class Parent{
constructor(){
if (
new.target.name ===
'Parent') {
throw new Error(
'本类禁止实例化!')
}
}
}
class Child extends Parent{
constructor(){
super()
}
}