Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I find the name of a JavaScript function

I have for example a function called "Apples()" and a function called "Pears()".
These are to be instantiated via various calls such as new Apples() or new Pears().
All of these new instances are to be stored in an array.

At some later point I want to scan through the array for instances of "Apples", but I am unable to find how to identify the Object I am retrieving.

I have overcome this difficulty by declaring this.type = "Apples" or this.type = "Pears" in each of the appropriate functions, but this seems a rather clumsy solution, particularly as the Google Chrome debugger is able to identify the Object type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The proposed solution "var prot = Object.prototype.toString.call(arrayEntry(i)) produces [object Object] – not at all useful unfortunately.

>Solution :

You can use the Object.getPrototypeOf() function to get the prototype. The constructor function will be in the prototype’s constructor property, and you can get its name from the name property.

function getClassName(obj) {
  return Object.getPrototypeOf(obj).constructor.name;
}

function Apples() {}
function Oranges() {}

a = new Apples();
o = new Oranges();

console.log(getClassName(a));
console.log(getClassName(o));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading