freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../object-oriented-programming/understand-the-constructor-...

2.5 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7daf367417b2b2512b7e Understand the Constructor Property 1 理解构造函数属性

Description

在以前的挑战中创建的对象实例duckbeagle上有一个特殊的constructor属性:
let duck = new Bird;
让beagle = new Dog;

console.logduck.constructor === Bird; //打印为true
console.logbeagle.constructor === Dog; //打印为true
请注意, constructor属性是对创建实例的构造函数的引用。 constructor属性的优点是可以检查此属性以找出它是什么类型的对象。以下是如何使用它的示例:
function joinBirdFraternitycandidate{
ifcandidate.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