Introduction to Objects 1 : Customizing Constructors


In addition to the basic Object constructor, we can define our own custom constructors. These are helpful for two reasons:

We can assign our objects properties through parameters we pass in when the object is created.
We can give our objects methods automatically.
These both work to save us time and lines of code when we make objects.

Notice that without the constructor, it takes us 3 lines of code to make harry_potter, an object that represents Harry Potter book 1.

Then in line 7 we introduce a constructor for a Book object, where we pass in the pages and author properties as parameters.

Use this constructor to make the_hobbit, a book with 320 pages by "J.R.R. Tolkien". Notice by using the constructor you can do this in only one line instead of three!

Why isn't this working?

// 3 lines required to make harry_potter
var harry_potter = new Object();
harry_potter.pages = 350; = "J.K. Rowling";

// A custom constructor for book
function Book(pages, author) {
this.pages = pages; = author;

// Use our new constructor to make the_hobbit in one line
var the_hobbit = new Book(320, 'J.R.R Tolkien');


What exactly is the error message?


Your code:


Oops, try again. Make sure that the_hobbit's author is J.R.R. Tolkien by passing it as the first argument to the Book constructor.


even though it says not to modify the constructor.


This is a well known typo in the instructions. Unfortunately there is no way to change it. Just make sure you include that full stop after the R.


Thank you, mtf for getting me past this.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.