0

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;
}
A Masters
  • 3
  • 3
  • You should check for ```oop``` concepts in javascript. – Nexo Jul 13 '22 at 16:19
  • 2
    i think you're looking for the `instanceof` operator. eg, `if (foo instanceof Apples) {` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof – Nicholas Tower Jul 13 '22 at 16:19
  • Does this answer your question? [The most accurate way to check JS object's type?](https://stackoverflow.com/questions/7893776/the-most-accurate-way-to-check-js-objects-type) – Heretic Monkey Jul 13 '22 at 16:21

2 Answers2

2

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));
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

This is how you can read the name member of a function object:

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

console.log(test.name)
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175