indieman
indieman

Reputation: 1121

Find out the class of an object in prototypejs

I use prototypejs Class API for class-based OOP.

Is there a way to get the class name of an an object?

EG:

var myDog = new Dog();
myDog.getClassName() //Should return "Dog"

Upvotes: 4

Views: 925

Answers (1)

João Silva
João Silva

Reputation: 91299

If you are using Prototypejs' create() function to create the class, you need to store an additional property to hold the name of the class, since the only reference to a class named Dog is the variable name to which you assign the result of create():

var Dog = Class.create({
  className: "Dog",

  initialize: function() {
  }
});

var myDog = new Dog();
console.log(myDog.className); // "Dog"

On the other hand, if you are defining your class with something along these lines:

function Dog() {
}

Then, you could just use Object#constructor:

myDog.constructor.name; // "Dog"

Upvotes: 5

Related Questions