从ES6的孩子获取父类名称? [英] Get parent class name from child with ES6?

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

问题描述

我想获得父类名( Parent ),但我只能使用此代码检索子类名(孩子)...

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) to得到 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屋!

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