Dec
6
JavaScript - Dynamic Prototype Method
December 6, 2007 |
Most traditional C and/or Java developers feel the hybrid constructor/prototype paradigm is rough, or simly not professional. To them, what is lacking is some sort of encapsulation of properties and methods when defining classes. Encapsulation aka Information hiding, is the hiding of design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed.
The basic idea behind dynamic prototyping is the same as the hybrid constructor/prototype paradigm: Nonfunction properties are defined in the constructor, whereas function properties are defined on the prototype property. The one difference is where the assignment of the methods takes place. Simply put, this method uses a flag (_initialized) to determine if the prototype has been assigned any methods yet. So in this way, we create a form of encapsulation.
Below is an example:
function CD(cTitle, cPrice, cArtist) {
this.title = cTitle;
this.price = cPrice;
this.artist = cArtist;
this.buyers = new Array("Tom", "Harry");
if (typeof CD._initialized == "undefined") {
CD.prototype.showTitle = function() {
alert(this.title);
}
CD._initialized = true;
}
}
var oCD1 = new CD("X&Y", 14, "coldplay");
var oCD2 = new CD("You Could Have It So Much Better", 12, "Franz");
oCD1.buyers.push("Matt");
alert(oCD1.buyers);
alert(oCD2.buyers);
oCD2.showTitle();
A test page can be seen at:
http://www.lab.highub.com/javascript/dynamic-prototype.html
Similar Posts
- None Found


































