使用 ES6 从孩子那里获取父类名称? [英] Get parent class name from child with ES6?
本文介绍了使用 ES6 从孩子那里获取父类名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取父类名称 (Parent
),但我只能使用此代码 (Child
) 检索子类名称..
I would like to get the parent class name (Parent
), but I'm only able to retrieve the child class name with this code (Child
)...
'use strict';
class Parent {
}
class Child extends Parent {
}
var instance = new Child();
console.log(instance.constructor.name);
有可能吗?
谢谢!
推荐答案
ES6 类相互继承.因此,当 instance.constructor
引用 Child
时,您可以使用 Object.getPrototypeOf(instance.constructor)
获取Parent
,然后访问 .name
:
ES6 classes inherit from each other. So when instance.constructor
refers to the Child
, then you can use Object.getPrototypeOf(instance.constructor)
to get the Parent
, and then access .name
:
Object.getPrototypeOf(instance.constructor).name // == "Parent"
当然,要使其正常工作,必须完全符合 ES6 标准和未压缩的代码.永远不要在代码中依赖函数名.
Of course, full ES6 compliance and non-minified code are necessary for this to work. You should never rely on function names in code.
这篇关于使用 ES6 从孩子那里获取父类名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文