2.9 KiB
2.9 KiB
id, title, challengeType, forumTopicId, localeTitle
| id | title | challengeType | forumTopicId | localeTitle |
|---|---|---|---|---|
| 587d7dad367417b2b2512b77 | Define a Constructor Function | 1 | 16804 | Определение функции конструктора |
Description
Constructors - это функции, которые создают новые объекты. Они определяют свойства и поведение, которые будут принадлежать новому объекту. Подумайте о них как о плане создания новых объектов. Вот пример constructor : функция Bird () {Этот
this.name = "Альберт";
this.color = "blue";
this.numLegs = 2;
}
constructor определяет объект Bird с name свойств, color и numLegs установленными на Albert, blue и 2, соответственно. Constructors следуют нескольким соглашениям: -
Constructorsопределяются с заглавным именем, чтобы отличать их от других функций, которые не являютсяconstructors. -
Constructorsиспользуют ключевое словоthisдля установки свойств объекта, который они создадут. Внутриconstructorthisотносится к новому объекту, который он создаст. -
Constructorsопределяют свойства и поведение вместо того, чтобы возвращать значение, как могли бы другие функции.
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');
- text: <code>Dog</code> should have a <code>color</code> property set to a string.
testString: assert(typeof (new Dog()).color === 'string');
- text: <code>Dog</code> should have a <code>numLegs</code> property set to a number.
testString: assert(typeof (new Dog()).numLegs === 'number');
Challenge Seed
Solution
function Dog (name, color, numLegs) {
this.name = 'name';
this.color = 'color';
this.numLegs = 4;
}