0

I want to check an object to see if any instances of the carDoor prototype exist

function carDoor(side) {
    this.side = side;
}

var Car = {

    "door1": new carDoor("left"),
    "door2": new carDoor("right")

}

Does the Car object have a door? - How can I check in a way that will work for any prototype?

Assume that you don't know or control the name of the property.

1

3 Answers 3

1

You can use the instanceof operator:

for (key in Car) {
   if (Car.hasOwnProperty(key)) {
      if (Car[key] instanceof carDoor) {
          // ...
      }
   }   
}
Sign up to request clarification or add additional context in comments.

2 Comments

What advantages / disadvantages does this approach have versus Car.door1.constructor === carDoor;?
@jt0dd instanceof operator also checks the inherited constructors but the constructor doesn't.
0

In your example, you could do:

Car.door1.constructor === carDoor;

That will return true.

5 Comments

And as far as naming convention goes, I would name them CarDoor and car.
Oh. Cool. I didn't know that constructed objects had that property.
Both answers (at the time of writing) that use the constructor property presuppose you know the name of the property; given that you're naming the property door1 (door2 etc.) checking for the existence of that property should surely be enough?
What if I'm developing a public library, and I need to check for a certain prototype instance where the user of the library can name the prototype instance whatever he/she wants? @DavidThomas
What if..? Well, that might have been useful information to add to your question, and left me feeling a little less bemused by your use-case.
0

You answered your question.. or at least a half of it, verify the constructor of the Car object properties and it'll return true.

if (Car.door2.constructor === carDoor)
// ...

1 Comment

Oh, didn't see @ramdog gave this answer too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.