2018-09-30 23:01:58 +01:00
---
id: 587d7dad367417b2b2512b78
title: Use a Constructor to Create Objects
challengeType: 1
2020-05-21 17:31:25 +02:00
isHidden: false
2019-07-31 11:32:23 -07:00
forumTopicId: 18233
2018-09-30 23:01:58 +01:00
---
## Description
< section id = 'description' >
Here's the < code > Bird< / code > 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();
```
2019-10-27 15:45:37 -01:00
Notice that the < code > new< / code > operator is used when calling a constructor. This tells JavaScript to create a new instance of < code > Bird< / code > called < code > blueBird< / code > . Without the < code > new< / code > operator, < code > this< / code > inside the constructor would not point to the newly created object, giving unexpected results.
2018-09-30 23:01:58 +01:00
Now < code > blueBird< / code > has all the properties defined inside the < code > Bird< / code > 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
```
2018-09-30 23:01:58 +01:00
< / section >
## Instructions
< section id = 'instructions' >
Use the < code > Dog< / code > constructor from the last lesson to create a new instance of < code > Dog< / code > , assigning it to a variable < code > hound< / code > .
< / section >
## Tests
< section id = 'tests' >
```yml
2018-10-04 14:37:37 +01:00
tests:
- text: < code > hound</ code > should be created using the < code > Dog</ code > constructor.
2019-07-24 02:32:04 -07:00
testString: assert(hound instanceof Dog);
2019-10-27 15:45:37 -01:00
- text: Your code should use the < code > new</ code > operator to create an instance of < code > Dog</ code > .
2019-07-24 02:32:04 -07:00
testString: assert(code.match(/new/g));
2018-09-30 23:01:58 +01:00
```
< / section >
## Challenge Seed
< section id = 'challengeSeed' >
< div id = 'js-seed' >
```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
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```js
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
const hound = new Dog();
```
< / section >