instance 。 JavaScript提供了一种使用instanceof运算符验证这一点的便捷方法。 instanceof允许您将对象与构造函数进行比较,根据是否使用构造函数创建该对象,返回true或false 。这是一个例子: 让Bird = function(名称,颜色){如果在不使用构造函数的
this.name = name;
this.color = color;
this.numLegs = 2;
}
让乌鸦=新鸟(“亚历克西斯”,“黑色”);
鸟的鸟; // =>是的
instanceof创建对象, instanceof将验证它不是该构造函数的实例: 让金丝雀= {
名称:“Mildred”,
颜色:“黄色”,
numLegs:2
};
鸟类的金丝雀; // => false
House构造函数的新实例,将其myHouse并传递多个卧室。然后,使用instanceof验证它是House的实例。 myHouse应该将numBedrooms属性设置为数字。
testString: 'assert(typeof myHouse.numBedrooms === "number", "myHouse should have a numBedrooms attribute set to a number.");'
- text: 请务必使用instanceof运算符验证myHouse是House的instanceof 。
testString: 'assert(/myHouse\s*instanceof\s*House/.test(code), "Be sure to verify that myHouse is an instance of House using the instanceof operator.");'
```