如何在JavaScript的Parent类中判断调用它的子类?
如何在Parent类内部识别调用它的子类
当然可以,有几种实用的方法能实现这个需求:
方法1:利用this.constructor获取子类
在父类构造函数里,this指向的是子类的实例,this.constructor就是对应的子类构造函数,通过它的name属性就能直接拿到子类名称:
class Parent { constructor () { console.log("parent"); const childClass = this.constructor; // 判断是否是子类调用 if (childClass !== Parent) { console.log(`当前被子类 ${childClass.name} 调用`); } } } class Child1 extends Parent { constructor() { console.log("child 1"); super(); } } class Child2 extends Parent { constructor() { console.log("child 2"); super(); } } const c1 = new Child1; // 输出顺序: // child 1 // parent // 当前被子类 Child1 调用 const c2 = new Child2; // 输出顺序: // child 2 // parent // 当前被子类 Child2 调用
方法2:使用ES6的new.target元属性(更严谨)
new.target是ES6新增的元属性,它会返回当前正在被new操作的构造函数。在父类构造函数中,当子类通过super()调用时,new.target会指向对应的子类构造函数:
class Parent { constructor () { console.log("parent"); if (new.target !== Parent) { console.log(`当前被子类 ${new.target.name} 调用`); } } } class Child1 extends Parent { constructor() { console.log("child 1"); super(); } } const c1 = new Child1; // 输出顺序: // child 1 // parent // 当前被子类 Child1 调用
注意点
- 如果直接实例化Parent类(
new Parent()),new.target和this.constructor都会等于Parent,这时候就能区分是父类自身实例化还是子类调用的场景。 new.target在函数不是通过new调用时会返回undefined,但这里我们都是通过new实例化类,所以不用担心这个问题。
内容的提问来源于stack exchange,提问作者Greeso
相关产品推荐
相关产品推荐

