5

If I create a Foo class using "traditional" Javascript classes, both chrome and Firefox will show the Foo name when printing Foo instances on the console:

function Foo(){
    this.x = 10;
}

console.log(new Foo());
// Foo {x: 10}

On the other hand, if I use hand rolled prototypal inheritance then I don't get the helpful name when debugging

function mkClass(init, proto){
    return function(/**/){
         var obj = Object.create(proto);
         init.apply(obj, arguments);
         return obj;
    }
}

var Bar = mkClass(function(){ this.x = 10 }, {});

console.log(Bar());
// Object {x: 10}

Is there a way to have classes created via my prototypal system show their name when printed on the console? So far, the only way I could think of is an ugly hack abusing eval to give different names to the currently anonymous constructor function that mkClass returns.

hugomg
  • 68,213
  • 24
  • 160
  • 246
  • Are you using Firebug or FF console? I'm getting `[object Object]` for both examples in FF. – Evan Davis Aug 05 '14 at 15:01
  • 1
    related: [Is there any non-eval way to create a function with a runtime-determined name?](http://stackoverflow.com/q/9479046/1048572) – Bergi Aug 05 '14 at 15:03
  • @Mathletics: you are right... I cant reproduce that anymore. I guess I must have been tripped up by the new FF tab layout that makes it similar to Chrome :) – hugomg Aug 05 '14 at 15:31

1 Answers1

2

It seems that FF and chrome just print constructor property. Try setting it to something meaningful and you should see the result.

function mkClass(init, proto){
    proto.constructor = {name: "Foo"};
    return function(/**/){
         var obj = Object.create(proto);
         init.apply(obj, arguments);
         return obj;
    }
}
hugomg
  • 68,213
  • 24
  • 160
  • 246
Anton L
  • 412
  • 4
  • 12
  • Setting the "constructor" property to a named function or to a `{name: "Foo"}` object works in Chrome. It doesnt do anything one Firefox though :( – hugomg Aug 05 '14 at 14:57
  • 2
    As @Mathletics mentioned, FF returns [object Object] even for your first example. So it seems that FF "knows" only standard types, all other types are displayed as "Object". – Anton L Aug 05 '14 at 15:18
  • 2
    CAUTION! This method cause the 'constructor' property to be listed among object's own properties (that is, `obj.hasOwnProperty('constructor') === true`, while objects created using standard method have it `false`) – Roman Bekkiev Aug 29 '14 at 07:53