Rudie
Rudie

Reputation: 53781

Get current 'class name' after class/prototype inheritance

I was playing with class/function/prototype inheritance a bit and got a decent setup working. Something simple that I understand.

http://jsfiddle.net/rudiedirkx/rwPeD/6/

For debugging purposes, I wanted to print in each constructor what kind of object was calling that constructor. For instance the Ronin constructor calls the Ninja constructor and that calls the Person constructor. For that I made a get_class function:

function get_class(obj) {
    var C = String(obj.__proto__.constructor);
    return C.match(/function (\w+)\(/, C)[1];
}

and that doesn't work. It always returns "Person". Why? Every 'class' has its own constructor, doesn't it? If I do a console.log(this) in every constructor, Chrome Devtools knows which type the object is. How do I get there (with vanilla JS)?

PS. Full output in my Chrome:

Chrome Devtools output

Upvotes: 8

Views: 10431

Answers (2)

ucdream
ucdream

Reputation: 691

I think the problem refers to following line. this.prototype.constructor points to what Person.prototype points to.

this.prototype = Object.create(sup.prototype);

You may need change its reference explicitly.

this.prototype.constructor = this;

The similar question can be found at Get name of derived constructor in Javascript

Upvotes: 0

Erich Horn
Erich Horn

Reputation: 1011

Or you could do something that actually works...

function getClass(obj) {
    return obj.__proto__.constructor.name;
}

obj.attr("class") only works if the method attr exists with it won't in a native environment.

Still your suggestion was very good in it's design.

Please note that proto.constructor.name will always return "Object" if the class is not a native class, such as Array, String, RegExp, Error, etc... If anyone knows how to convince the "name" property to return the real name, even if I have to add code to do it, I would buy him a banana for his/her trouble.

Upvotes: 6

Related Questions