2.8 KiB
2.8 KiB
id, title, challengeType, forumTopicId, localeTitle
id | title | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|
587d7dad367417b2b2512b78 | Use a Constructor to Create Objects | 1 | 18233 | Использование конструктора для создания объектов |
Description
Bird
из предыдущего вызова: функция Bird () {Обратите внимание, что
this.name = "Альберт";
this.color = "blue";
this.numLegs = 2;
// «this» внутри конструктора всегда ссылается на создаваемый объект
}
let blueBird = new Bird ();
new
оператор используется при вызове конструктора. Это говорит JavaScript для создания нового instance
Bird
под названием blueBird
. Без new
оператора this
внутри конструктора не будет указывать на вновь созданный объект, давая неожиданные результаты. Теперь blueBird
имеет все свойства, определенные внутри конструктора Bird
: blueBird.name; // => АльбертКак и любой другой объект, его свойства могут быть доступны и изменены:
blueBird.color; // => синий
blueBird.numLegs; // => 2
blueBird.name = 'Elvira';
blueBird.name; // => Эльвира
Instructions
Dog
из последнего урока, чтобы создать новый экземпляр Dog
, присвоив его переменной hound
.
Tests
tests:
- text: <code>hound</code> should be created using the <code>Dog</code> constructor.
testString: assert(hound instanceof Dog);
- text: Your code should use the <code>new</code> operator to create an <code>instance</code> of <code>Dog</code>.
testString: assert(code.match(/new/g));
Challenge Seed
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
// Add your code below this line
Solution
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
const hound = new Dog();