3.0 KiB
3.0 KiB
id, title, challengeType, forumTopicId, localeTitle
id | title | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|
587d7daf367417b2b2512b7e | Understand the Constructor Property | 1 | 301327 | Понять свойство конструктора |
Description
constructor
расположенное на объектных экземплярах duck
и beagle
которые были созданы в предыдущих задачах: let duck = new Bird ();Обратите внимание, что свойство
let beagle = new Dog ();
console.log (duck.constructor === Bird); // выводит true
console.log (beagle.constructor === Собака); // выводит true
constructor
является ссылкой на конструктор, создавший экземпляр. Преимущество свойства constructor
заключается в том, что можно проверить это свойство, чтобы узнать, какой он объект. Вот пример того, как это можно использовать: function joinBirdFraternity (кандидат) {Заметка
if (кандидат.конструктор === Птица) {
return true;
} else {
return false;
}
}
Поскольку свойство
constructor
может быть перезаписано (что будет рассмотрено в следующих двух задачах), лучше всего использовать метод instanceof
для проверки типа объекта.
Instructions
joinDogFraternity
function that takes a candidate
parameter and, using the constructor
property, return true
if the candidate is a Dog
, otherwise return false
.
Tests
tests:
- text: <code>joinDogFraternity</code> should be defined as a function.
testString: assert(typeof(joinDogFraternity) === 'function');
- text: <code>joinDogFraternity</code> should return true if<code>candidate</code> is an instance of <code>Dog</code>.
testString: assert(joinDogFraternity(new Dog("")) === true);
- text: <code>joinDogFraternity</code> should use the <code>constructor</code> property.
testString: assert(/\.constructor/.test(code) && !/instanceof/.test(code));
Challenge Seed
function Dog(name) {
this.name = name;
}
// Add your code below this line
function joinDogFraternity(candidate) {
}
Solution
function Dog(name) {
this.name = name;
}
function joinDogFraternity(candidate) {
return candidate.constructor === Dog;
}