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.

3 Answers3

1

You can use the instanceof operator:

for (key in Car) {
   if (Car.hasOwnProperty(key)) {
      if (Car[key] instanceof carDoor) {
          // ...
      }
   }   
}
Ram
  • 143,282
  • 16
  • 168
  • 197
  • What advantages / disadvantages does this approach have versus `Car.door1.constructor === carDoor;`? –  Jul 06 '14 at 00:47
  • 1
    @jt0dd `instanceof` operator also checks the inherited constructors but the `constructor` doesn't. – Ram Jul 06 '14 at 00:57
0

In your example, you could do:

Car.door1.constructor === carDoor;

That will return true.

ramdog
  • 486
  • 5
  • 8
  • And as far as naming convention goes, I would name them CarDoor and car. – ramdog Jul 06 '14 at 00:27
  • Oh. Cool. I didn't know that constructed objects had that property. –  Jul 06 '14 at 00:27
  • 1
    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? – David Thomas Jul 06 '14 at 00:31
  • 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 –  Jul 06 '14 at 00:45
  • 1
    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. – David Thomas Jul 06 '14 at 00:46
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)
// ...
Eduard
  • 3,395
  • 8
  • 37
  • 62