javascript 使用 ES6 从孩子那里获取父类名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31644662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get parent class name from child with ES6?
提问by Swadon
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
)...
我想获取父类名称 ( Parent
),但我只能使用此代码 ( Child
)检索子类名称...
'use strict';
class Parent {
}
class Child extends Parent {
}
var instance = new Child();
console.log(instance.constructor.name);
Is it possible ?
是否可以 ?
Thanks !
谢谢 !
回答by Bergi
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
:
ES6 类相互继承。所以当instance.constructor
指的是Child
,那么你可以使用Object.getPrototypeOf(instance.constructor)
来获取Parent
,然后访问.name
:
Object.getPrototypeOf(instance.constructor).name == "Parent";
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 合规性和非压缩代码是必要的。你永远不应该依赖代码中的函数名。
回答by Resist Design
Here is something amusing:
这里有一些有趣的事情:
class J {}
class K extends J {}
class L extends K {}
function getBaseClass(targetClass){
if(targetClass instanceof Function){
let baseClass = targetClass;
while (baseClass){
const newBaseClass = Object.getPrototypeOf(baseClass);
if(newBaseClass && newBaseClass !== Object && newBaseClass.name){
baseClass = newBaseClass;
}else{
break;
}
}
return baseClass;
}
}
console.log(getBaseClass(L)); // Will return J.
回答by loganfsmyth
You could technically do
你可以在技术上做到
// instanceProto === Child.prototype
var instanceProto = Object.getPrototypeOf(instance);
// parentProto === Parent.prototype
var parentProto = Object.getPrototypeOf(instanceProto);
console.log(parentProto.constructor.name);
keep in mind that these names may all be mangled by minifiers.
请记住,这些名称可能都被压缩器破坏了。
回答by Dariusz Filipiak
From protoproperty:
从原型属性:
Child['__proto__'].name
example here: https://stackblitz.com/edit/typescript-s5brk9