- , prototype, instanceof, .
: new -keyword, ( constuctor)
apply() , ; , , /.
- factory, . , new -keyword .
, , ( JS- , , , ,... )
, , - ()
, , , (, pro con.)
My goto-approach , :
( , factory ).
function Book(conf) {
var book = Object.create(Book.prototype);
if(typeof conf === "object"){
for(var k in conf) book[k] = conf[k];
}else if(conf){
book.name = String(conf);
}
return book;
}
Book.prototype.numPages = 0;
var myBook1 = Book("Peter Pan");
var myBook2 = Book({
name: "American Gods",
author: "Neil Gaiman"
});
, - Book
function Book(conf) {
if(conf instanceof Book) return conf;
var book = Object.create(Book.prototype);
return book;
}
var data = [
"Peter Pan",
{name: "American Gods"},
];
var books = data.map(Book);
-, .