简体   繁体   English

JavaScript-检查对象中是否存在原型实例

[英]JavaScript - check for existence of a prototype instance within an object

I want to check an object to see if any instances of the carDoor prototype exist 我想检查一个对象,以查看carDoor原型的任何实例是否存在

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. 假设您不知道或控制属性的名称。

You can use the instanceof operator: 您可以使用instanceof运算符:

for (key in Car) {
   if (Car.hasOwnProperty(key)) {
      if (Car[key] instanceof carDoor) {
          // ...
      }
   }   
}

In your example, you could do: 在您的示例中,您可以执行以下操作:

Car.door1.constructor === carDoor;

That will return true. 那将返回true。

You answered your question.. or at least a half of it, verify the constructor of the Car object properties and it'll return true. 您回答了问题..或至少回答了一半,请验证Car对象属性的构造函数,它将返回true。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM