2018-10-10 18:03:03 -04:00
---
id: 587d7dad367417b2b2512b78
2021-02-06 04:42:36 +00:00
title: Use a Constructor to Create Objects
2018-10-10 18:03:03 -04:00
challengeType: 1
2020-08-04 15:15:28 +08:00
forumTopicId: 18233
2021-01-13 03:31:00 +01:00
dashedName: use-a-constructor-to-create-objects
2018-10-10 18:03:03 -04:00
---
2020-12-16 00:37:30 -07:00
# --description--
2021-02-06 04:42:36 +00:00
Here's the `Bird` constructor from the previous challenge:
2020-08-04 15:15:28 +08:00
```js
function Bird() {
this.name = "Albert";
this.color = "blue";
this.numLegs = 2;
2021-02-06 04:42:36 +00:00
// "this" inside the constructor always refers to the object being created
2020-08-04 15:15:28 +08:00
}
let blueBird = new Bird();
```
2021-02-06 04:42:36 +00: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:
2020-08-04 15:15:28 +08:00
```js
blueBird.name; // => Albert
blueBird.color; // => blue
blueBird.numLegs; // => 2
```
2021-02-06 04:42:36 +00:00
Just like any other object, its properties can be accessed and modified:
2020-08-04 15:15:28 +08:00
```js
blueBird.name = 'Elvira';
blueBird.name; // => Elvira
```
2020-12-16 00:37:30 -07:00
# --instructions--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
Use the `Dog` constructor from the last lesson to create a new instance of `Dog` , assigning it to a variable `hound` .
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
# --hints--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
`hound` should be created using the `Dog` constructor.
2018-10-10 18:03:03 -04:00
```js
2020-12-16 00:37:30 -07:00
assert(hound instanceof Dog);
2018-10-10 18:03:03 -04:00
```
2021-02-06 04:42:36 +00:00
Your code should use the `new` operator to create an instance of `Dog` .
2020-08-04 15:15:28 +08:00
2018-10-10 18:03:03 -04:00
```js
2020-12-16 00:37:30 -07:00
assert(code.match(/new/g));
2018-10-10 18:03:03 -04:00
```
2020-08-04 15:15:28 +08:00
2021-01-13 03:31:00 +01:00
# --seed--
## --seed-contents--
```js
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
// Only change code below this line
```
2020-12-16 00:37:30 -07:00
# --solutions--
2021-01-13 03:31:00 +01:00
```js
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
const hound = new Dog();
```