You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:42:44