I am learning about the constructor pattern.
To exercise what I am learning, I am building an in-memory model called Book
inspired by the Mongoose API:
var assert = require("assert");
var Book = (function() {
var books = [];
var constructor = function(title, author, genre) {
assert.ok(title, "title cannot be undefined");
assert.ok(author, "author cannot be undefined");
assert.ok(genre, "genre cannot be undefined");
this.title = title;
this.author = author;
this.genre = genre;
this.save = function() {
books.push(this);
};
this.description = this.title + "is a " + this.genre + " by " + this.author;
};
constructor.find = function() {
return books;
};
return constructor;
}());
With this model, I can create Book
instances and save
them to an in-memory store:
var book = new Book("The Great Gatsby", "F. Scott Fitzgerald", "Novel");
book.save();
var books = Book.find();
console.log(books);
// [ { title: 'The Great Gatsby',
// author: 'F. Scott Fitzgerald',
// genre: 'Novel',
// save: [Function],
// description: 'The Great Gatsbyis a Novel by F. Scott Fitzgerald' } ]
How do I remove the function property "save" from the output? I only want to show the properties.
I need to know because, I want to send the book
to the client using Express and I do not want to convolute the response with functions.
(I come from a C# background and in C#, I would override a function in the System.Object
base class called ToString
that functions like console.log
use internally. I do not know of any equivalent in JavaScript.)
Yes, it's possible to override the default toString output: