Prototype
Tworząc obiekt dodajemy do niego pola. Możemy też jako pole dodać funkcję, wtedy jest to tzw metoda.
//constructor
function Book( title, year ) {
this.title = title,
this.year = year
this.getSummary = function() {}
}
Sprawi to, że metoda wykona się od razu. Jeżeli nie chcemy, by się tak stało, możemy użyć prototype do stworzenia metody.
//constructor
function Book( title, year ) {
this.title = title,
this.year = year
}
Book.prototype.getSummary = function() {
return this.title + ' was written in ' + this.year;
}
Używanie cudzego constructora
przejmie to wszystkie deklaracje pól, ale nie przejmie metod pochodzących z prototype
//constructor
function Magazine(title, year, month) {
Book.call(this, title, year);
this.month = month;
}
//inherit Prototype also (so all the methods)
Magazine.prototype = Object.create(Book.prototype);
//but then constructor of magazine is "Book" and should be "Magazine" so fix it:
Magazine.prototype.constructor = Magazine