有没有一种方法可以在父类中获取子类的名称? [英] Is there a way to get name of child class in parent class?

查看:52
本文介绍了有没有一种方法可以在父类中获取子类的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印超级类(A)中的类B或C的名称.有没有一种方法可以从上下文中推断出这一点?我必须将名称作为参数传递给super还是有更好的方法呢?

I am trying to print out the name of class B or C in it's super class (A). Is there a way to infer this somehow from the context? Do I have to pass in the names into super as a parameter or is there a better way of doing this?

class A {
  constructor(){
    console.log(klass_name) // klass_name is some code to get the name of class B,C
  }
}

class B extends A {
  constructor() {
    super();
  }
}

class c extends A {
  super();
}

推荐答案

是的,您可以通过两种方法在显示的位置访问它:

Yes, there are two ways you can access it where you've shown:

  • this.constructor.name (假设没有任何混乱),您可以在可以访问该实例的任何地方使用它
  • new.target.name (仅在构造函数中可用, new.target 在不属于函数调用的函数中 undefined new 操作)
  • this.constructor.name (assuming nothing has messed around with it), which you can use anywhere that has access to the instance
  • new.target.name (only available in the constructor, new.target is undefined in function calls that aren't part of a new operation)

但是除了记录目的之类的东西之外,超类很少需要了解有关子类的任何信息.

But other than logging purposes and such, it's rare for the superclass to need to know anything about the subclass.

示例:

class A {
  constructor(){
    console.log("this.constructor.name = " + this.constructor.name);
    console.log("new.target.name = " + new.target.name);
  }
}

class B extends A {
}

class C extends A {
}

new C;

constructor 属性是在类的原型上自动设置的,以引用该类的构造函数,从ES2015开始,函数(包括构造函数)在其上具有 name 属性给出他们的名字.由于实例是从原型继承的,因此可以在其上使用 constructor 来访问该构造函数及其 name .

The constructor property is automatically set up on a class's prototype to refer to the class's constructor, and as of ES2015 functions (including constructors) have a name property on them giving their name. Since the instance inherits from the prototype, you can use constructor on it to access that constructor and its name.

new.target 元属性在函数中可用,以指示 new 表达式的目标函数是什么.

The new.target metaproperty is available in functions to indicate what the target function of the new expression was.

侧面说明:当您的子类构造函数仅是对超类构造函数的调用时,您可以将其完全取消.JavaScript引擎会为您添加一个.

Side note: When your subclass constructor is nothing but a call to the superclass constructor, you can leave it off entirely. The JavaScript engine will add one for you.

这篇关于有没有一种方法可以在父类中获取子类的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆