6

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?

Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148

1 Answers1

3

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.

lanzz
  • 42,060
  • 10
  • 89
  • 98
  • 1
    So, as I feared, the name printed out by CDT does not come from the ecmascript specs. It is only a debugging convenience for the developer. I am fairly new to Javascript and I generally like prototype style, but I find it disappointing that libraries like dojo and extjs try to shoehorn in OO style of programming. I think that this muddles one of the better features of Javascript. – Andrew Eisenberg Sep 02 '12 at 16:12
  • 1
    Javascript is a _very_ OO language, and is actually quite flexible in it. There are lots of libraries building a typical class-based OO _on top_ of Javascript, and that usually works quite well. This is not necessarily a bad thing for either those libraries or Javascript itself. – lanzz Sep 02 '12 at 18:53