Dor Cohen
Dor Cohen

Reputation: 17080

How can I identify the prototype typeof?

I have 2 classes, base and child:

// base class
function circle(radius){
    this.radius = radius;
    return true;}

// child class
function pizza(flavour, radius){
    this.radius = radius;
    this.flavour = flavour;
    return true;}

// Inheritance
pizza.prototype = new circle();

Now I'm creating an instance of pizza:

var myPizza = new pizza("Onion", 5);

How can I now identify if this variable is circle or pizza?

I know I can add a function that will return me the name or hold property with the type name but I wondered if there is another way without changing any of my classes.

Thanks!

Upvotes: 0

Views: 55

Answers (2)

Olaf Horstmann
Olaf Horstmann

Reputation: 16882

you could use instanceof

var p = new pizza();
console.log(p instanceof pizza) //true
console.log(p instanceof circle) //true also

Upvotes: 1

steveukx
steveukx

Reputation: 4368

By setting the prototype of the pizza class to be an instance of the circle class, any instance of pizza will automatically inherit from circle. As a result the instanceof operator will check the constructor of the instance:

(new pizza) instanceof pizza; // true
(new circle) instanceof circle; // true

and will also walk up the prototype chain to check any other constructors that the instance inherits from too:

(new pizza) instanceof circle; // true
(new pizza) instanceof Object; // true

Because circle doesn't inherit from pizza though, you can check that something is a circle but not a pizza with:

(new circle) instanceof pizza; // false

Upvotes: 4

Related Questions