Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of object or class

Tags:

javascript

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?

like image 909
TJR Avatar asked Apr 25 '12 11:04

TJR


People also ask

How do I get the class name of an object in Python?

To get the class name of an instance in Python: Use the type() function and __name__ to get the type or class of the Object/Instance. Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.

How do I get the class name of an object in C++?

DefineClassName( MyClass ); Finally to Get the class name you'd do the following: ClassName< MyClass >::name();

How do you return a class name in Java?

The java. lang. Class. getName() returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.


2 Answers

Get your object's constructor function and then inspect its name property.

myObj.constructor.name 

Returns "myClass".

like image 79
Oleg V. Volkov Avatar answered Sep 28 '22 01:09

Oleg V. Volkov


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"
like image 43
Eduardo Cuomo Avatar answered Sep 28 '22 01:09

Eduardo Cuomo