Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 359
Rudie Avatar asked Jul 14 '12 03:07

Rudie


People also ask

How do I return a class name in JavaScript?

Access the name property on the object's constructor to get the class name of the object, e.g. obj.constructor.name . The constructor property returns a reference to the constructor function that created the instance object.

How does prototypal inheritance work?

The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the [[Prototype]] of an object, we use Object. getPrototypeOf and Object.


1 Answers

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.

like image 121
Erich Horn Avatar answered Oct 21 '22 23:10

Erich Horn