2018-09-30 23:01:58 +01:00
---
id: 587d7dad367417b2b2512b78
title: Use a Constructor to Create Objects
challengeType: 1
---
## 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();
```
2018-09-30 23:01:58 +01:00
Notice that the < code > new< / code > operator is used when calling a constructor. This tells JavaScript to create a new < code > instance< / code > 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.
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.
2018-10-20 21:02:47 +03:00
testString: assert(hound instanceof Dog, '< code > hound< / code > should be created using the < code > Dog< / code > constructor.');
2018-10-04 14:37:37 +01:00
- text: Your code should use the < code > new</ code > operator to create an < code > instance</ code > of < code > Dog</ code > .
2018-10-20 21:02:47 +03:00
testString: assert(code.match(/new/g), 'Your code should use the < code > new< / code > operator to create an < code > instance< / code > of < code > Dog< / code > .');
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;
}
// Add your code below this line
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```js
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
const hound = new Dog();
```
< / section >