freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../object-oriented-programming/verify-an-objects-construct...

2.3 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7dae367417b2b2512b7a Verify an Object's Constructor with instanceof 1 使用instanceof验证Object的构造函数

Description

无论何时构造函数创建一个新对象,该对象都被称为其构造函数的一个instance 。 JavaScript提供了一种使用instanceof运算符验证这一点的便捷方法。 instanceof允许您将对象与构造函数进行比较,根据是否使用构造函数创建该对象,返回truefalse 。这是一个例子:
让Bird = function名称颜色{
this.name = name;
this.color = color;
this.numLegs = 2;
}

让乌鸦=新鸟(“亚历克西斯”,“黑色”);

鸟的鸟; // =>是的
如果在不使用构造函数的instanceof创建对象, instanceof将验证它不是该构造函数的实例:
让金丝雀= {
名称“Mildred”
颜色:“黄色”,
numLegs2
};

鸟类的金丝雀; // => false

Instructions

创建House构造函数的新实例,将其myHouse并传递多个卧室。然后,使用instanceof验证它是House的实例。

Tests

tests:
  - text: <code>myHouse</code>应该将<code>numBedrooms</code>属性设置为数字。
    testString: 'assert(typeof myHouse.numBedrooms === "number", "<code>myHouse</code> should have a <code>numBedrooms</code> attribute set to a number.");'
  - text: 请务必使用<code>instanceof</code>运算符验证<code>myHouse</code>是<code>House</code>的<code>instanceof</code> 。
    testString: 'assert(/myHouse\s*instanceof\s*House/.test(code), "Be sure to verify that <code>myHouse</code> is an instance of <code>House</code> using the <code>instanceof</code> operator.");'

Challenge Seed

/* jshint expr: true */

function House(numBedrooms) {
  this.numBedrooms = numBedrooms;
}

// Add your code below this line

Solution

// solution required