在Javascript中获取派生构造函数的名称

Jes*_*dge 2 javascript inheritance

是否可以在以下示例中获取派生的"类"的名称?我想以某种方式将输出设置为"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)
Run Code Online (Sandbox Code Playgroud)

我意识到我可以this.my_type = 'ChildClass'在ChildClass构造函数中做,但是我有许多扩展ParentClass的类,并且在任何地方都这样做会很不方便.

Aad*_*hah 5

在你的情况下的问题是你覆盖了prototype属性,ChildClass但你没有重置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
Run Code Online (Sandbox Code Playgroud)

现在您的代码将按预期工作.以下答案解释了原始代码无效的原因: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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

var ChildClass = defclass(ParentClass, function () {
    this.constructor = function () {
        this.name = "Fred";
    };
});
Run Code Online (Sandbox Code Playgroud)

这种方法有几个优点:

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

希望有所帮助.