I am trying to determine the rules for generating class names in javascript. I pasted this script into Chrome dev tools console:
var obj = {
Constr : function() { }
};
var obj2 = obj;
console.log(new obj.Constr());
console.log(new obj2.Constr());
obj2.Constr2 = function() { };
console.log(new obj.Constr2());
console.log(new obj2.Constr2());
And here are the results in the console:
obj.Constr
obj.Constr
obj2.Constr2
obj2.Constr2
It seems that the name of the class is determined by the variable that the constructor function was originally assigned to. I am looking for the precise rules that CDT uses to generate this name. Also, is this the same name that the Google Closure Compiler recognizes?
I have tried to see if I can reproduce similar behavior in Firebug, but I can't seem to get class names to print out in the console. As a secondary question, does anyone know how to see this in firebug?
There are no classes in Javascript, as it is prototype-based OOP, not class-based. Chrome apparently does some deducing in order to print some description of the object in the console, but that is not standard Javascript — in the standard, objects have no named class, and you cannot figure out the name of the class the object belongs to, since the only inheritance is done through the actual [[Prototype]]
internal pseudo-property, which is also an object in its own right, with no name or "class". Usually, you might deduce something similar to a class name by looking at object.__proto__.constructor.name
, which would return the name of the function which is the constructor from which the object was instantiated; but this function might be anonymous, or your browser might not support the non-standard __proto__
property, or the prototype of the object might not contain a correct reference to its constructor. Generally, you cannot know the "class" of an object in JS; you can only test for descendancy (object instanceof Constructor
), but that is still implemented according to the constructor
property in the object prototype, which might be incorrect.