The object constructor allows us to use a function to build objects from structured data. At first glance it looks almost like a CSV import function.
function Book(title, author, description, price, isbn, count) {
this.title = title;
this.author = author;
this.description = description;
this.price = price;
this.isbn = isbn;
this.type = "Book";
this.count = count;
} // Skip the semicolon this time (?)
var war_peace = new Book("War and Peace","Leo Tolstoy","In Russia's struggle with Napoleon, Tolstoy saw a tragedy that involved all mankind.",99,"0192833987",587287);
var cat_hat = new Book("The Cat in the Hat","Dr. Seuss","Poor Dick and Sally. It's cold and wet and they're stuck in the house with nothing to do.",7.5,"039480001X",1626);
First we create a function with an apt name and include parameters for each key (field) in the new object we're creating, separated by commas.
function Book(title, description, price, isbn) {
Then we add those keys, constructor shorthand style...hmm.
this.title = title;
this.author = author;
etc...
We can even add key|value pairs with global values for all new objects.
this.type = "Book";
Next step we create the object variable, object constructor style, with its comma separated key values.
var war_peace = new Book("Leo Tolstoy","In Russia's struggle with Napoleon, Tolstoy saw a tragedy that involved all mankind.",99,"0192833987",587287);
That's pretty simple, actually.
Using object data
Now we can use the object data in output, like this:
console.log(war_peace.title + " is a " + war_peace.type + " by " + war_peace.author + ". You can buy it for $" + war_peace.price + ". ");
// War and Peace is a Book by Leo Tolstoy. You can buy it for $99.
Method inside a Constructor
Even better, we can use method inside of a constructor. I'm going to attempt doing that by adding a method to calculate how long it would take to read any given book, based on your wpm.
We're going to add the following method to the Book()
object:
this.readTime = function(wpm) {
return this.title + " contains " + this.count + " words and, at " + wpm + " words per minute, will take you " + Math.floor(this.count / wpm /60) + " hours and " + Math.floor((this.count / wpm) - (Math.floor(this.count / wpm /60) * 60)) + " minutes to read.";
};
And add the following function call and console.log to tell us a little about our book:
var yourTime = war_peace.readTime(prompt("How many words per minute do you read?"));
console.log(war_peace.title + " is a " + war_peace.type + " by " + war_peace.author + ". You can buy it for $" + war_peace.price + ". " + yourTime);
// War and Peace is a Book by Leo Tolstoy. You can buy it for $99. War and Peace contains 587287 words and, at 72 words per minute, will take you 135 hours and 56 minutes to read.
Next we're looking at objects in array.