How does Chrome and Firefox print the class name of an object in the console?

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

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

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

      

On the other hand, if I use routine prototypal inheritance then I don't get a useful 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 for classes created through my prototype system to display their name when printed to the console? So far, the only way I could think of is an ugly hack abusing eval to give different names for the current anonymous constructor function returned by mkClass.

+3


source to share


1 answer


It seems like FF and chrome will just print the constructor property . Try to install 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;
    }
}

      

+2


source







All Articles