Files
2022-01-20 20:30:18 +01:00

2.4 KiB

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
587d7dae367417b2b2512b7a instanceof を使用してオブジェクトのコンストラクターを検証する 1 301337 verify-an-objects-constructor-with-instanceof

--description--

コンストラクター関数が新しいオブジェクトを生成するときはいつでも、そのオブジェクトはコンストラクターのインスタンスである、という言い方をします。 JavaScript にはそのことを検証するための便利な手段として instanceof 演算子が用意されています。 instanceof を使用してオブジェクトとコンストラクターを比較し、そのオブジェクトがそのコンストラクターを使用して作成されたかどうかに基づいて true または false を返すことができます。 例を示します。

let Bird = function(name, color) {
  this.name = name;
  this.color = color;
  this.numLegs = 2;
}

let crow = new Bird("Alexis", "black");

crow instanceof Bird;

この instanceof メソッドは true を返します。

オブジェクトがコンストラクターを使用せずに作成された場合、instanceof はオブジェクトがそのコンストラクターのインスタンスではないことを検証します。

let canary = {
  name: "Mildred",
  color: "Yellow",
  numLegs: 2
};

canary instanceof Bird;

この instanceof メソッドは false を返します。

--instructions--

House コンストラクターの新しいインスタンスを作成し、それに myHouse という名前を付けて、いくつかの寝室を渡してください。 次に、instanceof を使用して、House のインスタンスであることを検証してください。

--hints--

myHousenumBedrooms 属性に数値を設定する必要があります。

assert(typeof myHouse.numBedrooms === 'number');

instanceof 演算子を使用して、myHouseHouse のインスタンスであることを検証する必要があります。

assert(/myHouse\s*instanceof\s*House/.test(code));

--seed--

--seed-contents--

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

// Only change code below this line

--solutions--

function House(numBedrooms) {
  this.numBedrooms = numBedrooms;
}
const myHouse = new House(4);
console.log(myHouse instanceof House);