【发布时间】:2014-01-01 03:18:08
【问题描述】:
是否可以在下面的示例中获取派生“类”的名称?我想以某种方式将输出设为“ChildClass”,但改为“ParentClass”。
function ParentClass() { this.name = 'Bob' }
function ChildClass() { this.name = 'Fred' }
ChildClass.prototype = Object.create(ParentClass.prototype);
var child_instance = new ChildClass()
console.log('ChildClass type:', child_instance.constructor.name)
我意识到我可以在 ChildClass 构造函数中执行 this.my_type = 'ChildClass',但是我有很多扩展 ParentClass 的类,并且在任何地方都这样做会很不方便。
【问题讨论】:
-
@SLaks 继承没问题。问题是 OP 没有重置
constructor属性。阅读以下答案:stackoverflow.com/a/8096017/783743 -
@AaditMShah:没错。这就是我在博文末尾解释的内容。