Get name of object or class
Is there any solution to get the function name of an object?
function alertClassOrObject (o) {
window.alert(o.objectName); //"myObj" OR "myClass" as a String
}
function myClass () {
this.foo = function () {
alertClassOrObject(this);
}
}
var myObj = new myClass();
myObj.foo();
for (var k in this) {...}
- there is no information about the className
or ObjectName
. Is it possible to get one of them?
Get your object's constructor function and then inspect its name property.
myObj.constructor.name
Returns "myClass".
Example:
function Foo () { console.log('Foo function'); }
var f = new Foo();
console.log('f', f.constructor.name); // -> "Foo"
var Bar = function () { console.log('Anonymous function (as Bar)'); };
var b = new Bar();
console.log('b', b.constructor.name); // -> "Bar"
var Abc = function Xyz() { console.log('Xyz function (as Abc)'); };
var a = new Abc();
console.log('a', a.constructor.name); // -> "Xyz"
class Clazz { constructor() { console.log('Clazz class'); } }
var c = new Clazz();
console.log('c', c.constructor.name); // -> "Clazz"
var otherClass = class Cla2 { constructor() { console.log('Cla2 class (as otherClass)'); } }
var c2 = new otherClass();
console.log('c2', c2.constructor.name); // -> "Cla2"