2.5 KiB
2.5 KiB
id, title, challengeType
| id | title | challengeType |
|---|---|---|
| 587d7dad367417b2b2512b77 | Define a Constructor Function | 1 |
Description
Constructors are functions that create new objects. They define properties and behaviors that will belong to the new object. Think of them as a blueprint for the creation of new objects.
Here is an example of a constructor:
function Bird() {This
this.name = "Albert";
this.color = "blue";
this.numLegs = 2;
}
constructor defines a Bird object with properties name, color, and numLegs set to Albert, blue, and 2, respectively.
Constructors follow a few conventions:
Constructorsare defined with a capitalized name to distinguish them from other functions that are notconstructors.Constructorsuse the keywordthisto set properties of the object they will create. Inside theconstructor,thisrefers to the new object it will create.Constructorsdefine properties and behaviors instead of returning a value as other functions might.
Instructions
constructor, Dog, with properties name, color, and numLegs that are set to a string, a string, and a number, respectively.
Tests
tests:
- text: <code>Dog</code> should have a <code>name</code> property set to a string.
testString: 'assert(typeof (new Dog()).name === "string", "<code>Dog</code> should have a <code>name</code> property set to a string.");'
- text: <code>Dog</code> should have a <code>color</code> property set to a string.
testString: 'assert(typeof (new Dog()).color === "string", "<code>Dog</code> should have a <code>color</code> property set to a string.");'
- text: <code>Dog</code> should have a <code>numLegs</code> property set to a number.
testString: 'assert(typeof (new Dog()).numLegs === "number", "<code>Dog</code> should have a <code>numLegs</code> property set to a number.");'
Challenge Seed
Solution
function Dog (name, color, numLegs) {
this.name = 'name';
this.color = 'color';
this.numLegs = 4;
}