2018-09-30 23:01:58 +01:00
---
id: 587d7dad367417b2b2512b78
title: Use a Constructor to Create Objects
challengeType: 1
2019-07-31 11:32:23 -07:00
forumTopicId: 18233
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --description--
Here's the `Bird` constructor from the previous challenge:
2019-05-17 06:20:30 -07:00
```js
function Bird() {
this.name = "Albert";
this.color = "blue";
this.numLegs = 2;
// "this" inside the constructor always refers to the object being created
}
let blueBird = new Bird();
```
2020-11-27 19:02:05 +01:00
Notice that the `new` operator is used when calling a constructor. This tells JavaScript to create a new instance of `Bird` called `blueBird` . Without the `new` operator, `this` inside the constructor would not point to the newly created object, giving unexpected results. Now `blueBird` has all the properties defined inside the `Bird` constructor:
2019-05-17 06:20:30 -07:00
```js
blueBird.name; // => Albert
blueBird.color; // => blue
blueBird.numLegs; // => 2
```
2018-09-30 23:01:58 +01:00
Just like any other object, its properties can be accessed and modified:
2019-05-17 06:20:30 -07:00
```js
blueBird.name = 'Elvira';
blueBird.name; // => Elvira
```
2020-11-27 19:02:05 +01:00
# --instructions--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
Use the `Dog` constructor from the last lesson to create a new instance of `Dog` , assigning it to a variable `hound` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
`hound` should be created using the `Dog` constructor.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(hound instanceof Dog);
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
Your code should use the `new` operator to create an instance of `Dog` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(code.match(/new/g));
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --seed--
## --seed-contents--
2018-09-30 23:01:58 +01:00
```js
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
2020-03-08 07:46:28 -07:00
// Only change code below this line
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
```js
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
const hound = new Dog();
```