最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin8浏览0评论

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() {
    // klass_name is some code to get the name of class B,C
    console.log(klass_name)
  }
}

class B extends A {
}

class C extends A {
}

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() {
    // klass_name is some code to get the name of class B,C
    console.log(klass_name)
  }
}

class B extends A {
}

class C extends A {
}
Share Improve this question edited May 19, 2024 at 11:40 dumbass 27.2k4 gold badges36 silver badges73 bronze badges asked Dec 12, 2016 at 9:44 Ryan-Neal MesRyan-Neal Mes 6,26310 gold badges54 silver badges80 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 29

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 has the value 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;

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.

The new.target meta-property is available in functions to provide a reference to the constructor function that was used in the new expression.


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.

An instance can get a hold of its constructor function via this.constructor. The name of the function is available as the property .name. So, it's surprisingly straight forward:

console.log(this.constructor.name)
this.constructor.name

Should do the trick.

发布评论

评论列表(0)

  1. 暂无评论