Using object constructor


#1

I bumped into a code and I thought of writing it with object constructors in order to avoid repeating.
Here is the original code:

var library = [
{
title: ‘Bill Gates’,
author: ‘The Road Ahead’,
readingStatus: true
},
{
title: ‘Steve Jobs’,
author: ‘Walter Isaacson’,
readingStatus: true
},
{
title: ‘Mockingjay: The Final Book of The Hunger Games’,
author: ‘Suzanne Collins’,
readingStatus: false
}];

for (var i = 0; i < library.length; i++)
{
var book = “’” + library[i].title + “’” + ’ by ’ + library[i].author + “.”;
if (library[i].readingStatus) {
console.log("Already read " + book);
} else
{
console.log("You still need to read " + book);
}
}

Here is the code I came up with.

function Library (title, author, readingStatus){
this.title = title;
this.author = author;
this.readingStatus = readingStatus;
}

var gates = new.Library(“Bill gates”, “The Road Ahead”, true);
var js =new.Library(“eloquent JavaScript”, “who knows” , true);
var HungerGames = new.Library(“Hunger games”, “susanne”, false);

for (var i = 0; i < Library.length; i++)
{
var book = “’” + Library[i].title + “’” + ’ by ’ + Library[i].author + “.”;
if (Library[i].readingStatus) {
window.alert("Already read " + book);
} else
{
window.alert("You still need to read " + book);
}
}

but it says “unexpected identifier”.What is the problem here?


#2

This is going to cause problems, so we could start with that. Library is a function, and functions do not have a length attribute. It won’t show up as a syntax error, but will throw an exception at run time.

Without a line number, one would have to trace through the code for the actual error, assuming it can be found. First things first… Fix the error we spotted and run again. Expect more errors, but maybe this time different.

for (var i = 0; i < Library.length; i++) {}

How do we fix this?

function Book(title, author, flag) {
    this.title = title;
    this.author = author;
    this.isRead = flag;
}

var library = [
    new Book("The Road Ahead", "Bill Gates", true),
    new Book("Eloquent JavaScript", "Marijn Haverbeke" , true),
    new Book("Hunger Games", "Suzanne Collins", false)
];

for (var i = 0; i < library.length; i++) {
    console.log((library[i].isRead ? 'Already' : 'Still need to'), 'read', library[i].title, 'by', library[i].author);
}

As for the last loop, we can refine it by adding a method to the constructor prototype…

Book.prototype.readStatus = function() {
    return (this.isRead ? 'Already' : 'Still need to') + ' read ' + this.title + ' by ' + this.author;
};

for (var i = 0; i < library.length; i++) {
    console.log(library[i].readStatus());
}
Already read The Road Ahead by Bill Gates
Already read Eloquent JavaScript by Marijn Haverbeke
Still need to read Hunger Games by Suzanne Collins

#3

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