Get the name of a derived constructor in Javascript

Is it possible to get the name of the derived "class" in the following example? I would like to somehow get the output of "ChildClass", but instead it is "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)

I understand what I can do this.my_type = 'ChildClass'in the ChildClass constructor, but I have many classes that extend the ParentClass, and it will be inconvenient to do this everywhere.

+2
source share
1 answer

The problem in your case is that you are overwriting the property prototype ChildClass, but not redirecting the property constructoron the new prototype. You need to add one additional line:

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

, . , : fooobar.com/questions/85508/...

"", , . , , , . :

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";
    };
});

:

  • .
  • - .
  • .
  • .
  • .

, .

+4

All Articles