2.5 KiB
2.5 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d7daf367417b2b2512b7e | Understand the Constructor Property | 1 | 理解构造函数属性 |
Description
duck
和beagle
上有一个特殊的constructor
属性: let duck = new Bird();请注意,
让beagle = new Dog();
console.log(duck.constructor === Bird); //打印为true
console.log(beagle.constructor === Dog); //打印为true
constructor
属性是对创建实例的构造函数的引用。 constructor
属性的优点是可以检查此属性以找出它是什么类型的对象。以下是如何使用它的示例: function joinBirdFraternity(candidate){注意
if(candidate.constructor === Bird){
返回true;
} else {
返回虚假;
}
}
由于
constructor
属性可以被覆盖(将在接下来的两个挑战中讨论),因此通常最好使用instanceof
方法来检查对象的类型。 Instructions
joinDogFraternity
函数,该函数接受candidate
参数,并且如果候选者是Dog
,则使用constructor
属性返回true
,否则返回false
。 Tests
tests:
- text: <code>joinDogFraternity</code>应该被定义为一个函数。
testString: 'assert(typeof(joinDogFraternity) === "function", "<code>joinDogFraternity</code> should be defined as a function.");'
- text: 如果<code>candidate</code>是<code>Dog</code>一个实例, <code>joinDogFraternity</code>应该返回true。
testString: 'assert(joinDogFraternity(new Dog("")) === true, "<code>joinDogFraternity</code> should return true if<code>candidate</code> is an instance of <code>Dog</code>.");'
- text: <code>joinDogFraternity</code>应该使用<code>constructor</code>属性。
testString: 'assert(/\.constructor/.test(code) && !/instanceof/.test(code), "<code>joinDogFraternity</code> should use the <code>constructor</code> property.");'
Challenge Seed
function Dog(name) {
this.name = name;
}
// Add your code below this line
function joinDogFraternity(candidate) {
}
Solution
// solution required