JSFiddle - React, Tailwind, and code Playground
by gene
JavaScript
function Document(id, title) {
this.id = id;
this.title = title;
}
// Here prototype is used to factor out behavior
Document.prototype.document = function() { return this; }
Document.prototype.toString = function() { return 'Document [' + this.id + ']: "' + this.title + '"'; }
var PostingBehavior = {
toString: function() { return this.document().toString() + ' at rank ' + this.rank; },
document: function() { return Object.getPrototypeOf(this); }
}
function Posting(query, rank) {
this.query = query;
this.rank = rank;
}
function createPosting(query, document, rank) {
// here prototype is used to share data
Posting.prototype = document;
var posting = new Posting(query, rank);
// this applies the behavior
for (var fcnName in PostingBehavior) {
var fcn = PostingBehavior[fcnName];
posting[fcnName] = fcn;
}
return posting;
}
var doc = new Document('doc1', 'Lorem ipsum');
var p1 = createPosting('q1', doc, 1);
doc.title = 'Lorem ipsum (revised)';
console.log(p1);
alert(p1.toString());