Home > OS >  How can I find the name of a JavaScript function
How can I find the name of a JavaScript function

Time:07-14

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.

The proposed solution

"var prot = Object.prototype.toString.call(arrayEntry(i)) 

produces [object Object] - not at all useful unfortunately.

This works well:

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;
}

CodePudding user response:

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));

CodePudding user response:

const test = () => console.log(test)

console.log(test.name)

  • Related