Get current 'class name' after class/prototype inheritance

10,130

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.

Share:
10,130
Rudie
Author by

Rudie

I'm a web developer that likes cutting edges and doesn't like the backward kind of compatibility.

Updated on June 16, 2022

Comments

  • Rudie
    Rudie almost 2 years

    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