【问题标题】:Get name of derived constructor in Javascript在Javascript中获取派生构造函数的名称
【发布时间】: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 的类,并且在任何地方都这样做会很不方便。

【问题讨论】:

标签: javascript inheritance


【解决方案1】:

您的问题是您正在覆盖 ChildClassprototype 属性,但您没有重置新原型上的 constructor 属性。你需要多加一行:

function ParentClass() {
    this.name = "Bob";
}

function ChildClass() {
    this.name = "Fred";
}

ChildClass.prototype = Object.create(ParentClass.prototype);

ChildClass.prototype.constructor = ChildClass; // add this line to your code

现在您的代码将按预期工作。以下答案解释了为什么您的原始代码不起作用:https://stackoverflow.com/a/8096017/783743

我个人不喜欢写这样的“类”,构造函数和原型分别悬空。打字太乏味,语无伦次,眼睛疼痛且难以维护。因此,我使用以下实用函数来创建类:

function defclass(base, body) {
    var uber = base.prototype;
    var prototype = Object.create(uber);
    var constructor = (body.call(prototype, uber), prototype.constructor);
    constructor.prototype = prototype;
    return constructor;
}

现在您可以按如下方式创建类:

var ParentClass = defclass(Object, function () {
    this.constructor = function () {
        this.name = "Bob";
    };
});

var ChildClass = defclass(ParentClass, function () {
    this.constructor = function () {
        this.name = "Fred";
    };
});

这种方法有几个优点:

  1. 继承和类定义合二为一。
  2. 构造函数只是另一个原型方法。
  3. 一切都很好地封装在一个闭包中。
  4. 调用基类原型方法很容易。
  5. 您可以轻松创建私有静态函数。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2013-01-12
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2014-02-03
    • 2018-07-21
    相关资源
    最近更新 更多