2.8 KiB
2.8 KiB
id, title, challengeType
id | title | challengeType |
---|---|---|
587d7daf367417b2b2512b7e | Understand the Constructor Property | 1 |
Description
constructor
property located on the object instances duck
and beagle
that were created in the previous challenges:
let duck = new Bird();Note that the
let beagle = new Dog();
console.log(duck.constructor === Bird); //prints true
console.log(beagle.constructor === Dog); //prints true
constructor
property is a reference to the constructor function that created the instance.
The advantage of the constructor
property is that it's possible to check for this property to find out what kind of object it is. Here's an example of how this could be used:
function joinBirdFraternity(candidate) {Note
if (candidate.constructor === Bird) {
return true;
} else {
return false;
}
}
Since the
constructor
property can be overwritten (which will be covered in the next two challenges) it’s generally better to use the instanceof
method to check the type of an object.
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'', ''<code>joinDogFraternity</code> should be defined as a 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, ''<code>joinDogFraternity</code> should return true if<code>candidate</code> is an instance of <code>Dog</code>.'');'
- text: <code>joinDogFraternity</code> should use the <code>constructor</code> property.
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
function Dog(name) {
this.name = name;
}
function joinDogFraternity(candidate) {
return candidate.constructor === Dog;
}