Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

javascript - Is there a way to get name of child class in parent class?

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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  • 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.

Example:

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...