How to get 'class' name like Chrome's dev console?

183 Views Asked by At

Below is a piece of code evaluated in Chrome's console. A function constructor is created anonymously and used to construct an object. Chrome happily prints the real constructor's name 'Foo'. But, I can't find a way to get it using standard JS. Where's the magic?

> var exports = {}
undefined
> (function(){var Foo = function() {}; Foo.prototype = "";  exports.bar = Foo;})()
undefined
> obj = new exports.bar();
Foo {}
> obj.constructor.name
'Object'
> obj.__proto__
{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
> obj.__proto__.name
undefined
> obj
Foo {}
1

There are 1 best solutions below

2
Stephen Gilboy On

To get Foo you can exports.bar.name

if (obj.__proto__.isPrototypeOf(exports.bar)) {
  console.log(exports.bar.name);
}