2.0 KiB
id, title, challengeType, forumTopicId, dashedName
| id | title | challengeType | forumTopicId | dashedName |
|---|---|---|---|---|
| 587d7dae367417b2b2512b7a | Überprüfe den Konstruktor eines Objekts mit instanceof | 1 | 301337 | verify-an-objects-constructor-with-instanceof |
--description--
Immer wenn eine Konstruktorfunktion ein neues Objekt erzeugt, wird dieses Objekt als Instanz des Konstruktors bezeichnet. JavaScript bietet mit dem Operator instanceof eine praktische Möglichkeit, dies zu überprüfen. instanceof ermöglicht es dir, ein Objekt mit einem Konstruktor zu vergleichen und true oder false zurückzugeben, je nachdem, ob das Objekt mit dem Konstruktor erstellt wurde oder nicht. Hier ist ein Beispiel:
let Bird = function(name, color) {
this.name = name;
this.color = color;
this.numLegs = 2;
}
let crow = new Bird("Alexis", "black");
crow instanceof Bird;
Diese Methode instanceof würde true zurückgeben.
Wenn ein Objekt ohne einen Konstruktor erstellt wird, bestätigt instanceof, dass es nicht eine Instanz dieses Konstruktors ist:
let canary = {
name: "Mildred",
color: "Yellow",
numLegs: 2
};
canary instanceof Bird;
Diese Methode instanceof würde false zurückgeben.
--instructions--
Erstelle eine neue Instanz des Konstruktors House, nenne sie myHouse und übergebe eine Anzahl von Schlafzimmern. Verwende dann instanceof, um zu überprüfen, ob es sich um eine Instanz von House handelt.
--hints--
myHouse sollte ein Attribut numBedrooms besitzen, das auf eine Zahl gesetzt ist.
assert(typeof myHouse.numBedrooms === 'number');
Du solltest überprüfen, ob myHouse eine Instanz von House ist, indem du den Operator instanceof verwendest.
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);