-1

I' m building a system on top of John Resig' s class inheritance implementation (javascript)

All works well except for the fact that for inspecting/debugging purposes (and perhaps for typechecking later on, I'd like to have a handle on the actual name of the instantiated Class.

e.g: following the example from John, return Ninja instead of Class.

I'm aware that this name is coming from this.__proto__.constructor.name but this prop is readonly. I guess it has to be part of the initialization of the subclasss itself.

Anyone?

cweiske
  • 30,033
  • 14
  • 133
  • 194
Geert-Jan
  • 18,623
  • 16
  • 75
  • 137

1 Answers1

0

If you look at the code closely, you'll see a couple of lines like this:

Foo.prototype = new ParentClass;//makes subclass
Foo.prototype.constructor = Foo;

If you were to omit the second line, than the constructor name will be that of the the parent class. The name property might well be read-only, but the prototype isn't, nor is the constructor property of the prototype. That's how you can set the name of a "class"/constructor.

Also note that __proto__ is not the way to get an object's prototype. Best use this snippet:

var protoOf = Object && Object.getPrototypeOf ? Object.getPrototypeOf(obj) : obj.prototype;
//obviously followed by:
console.log(protoOf.constructor.name);
//or:
protoOf.addProtoMethod = function(){};//it's an object, thus protoOf references it
//or if all you're after is the constructor name of an instance:
console.log(someInstance.constructor.name);//will check prototype automatically

It's as simple as that, really.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149