Dec
5
JavaScript - Hybrid constructor/prototype
December 5, 2007 |
In one of my previous posts JavaScript - Constructor vs Prototype, I explained these two JavaScript paradigms seperately. Now let’s see what we can do by combining these two. Hybrid constructor/prototype paradigm is the dominant paradigm form used in JavaScript development. People use this form of paradigm to achieve the objective that functions are only created once, but each object can have its own instance of object properties.
So how to achieve the objective? The way of doing it is very simple: Use the constructor paradigm to define all nonfunction properties of the object and use the prototype paradigm to define the function properties (methods) of the object.Let’s see an example:
function CD(cTitle, cPrice, cArtist) {
this.title = cTitle;
this.price = cPrice;
this.artist = cArtist;
this.buyers = new Array("Tom", "Harry");
}
CD.prototype.showTitle = function() {
alert(this.title);
}
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();
In the example, Only one instance of the showTitle() function is being created, so there is no waste of memory. Besides, when oCD1 adds new buyer to the buyers array, it has no effect on oCD2’s buyers.
Below is the link to the test page:
http://www.lab.highub.com/javascript/constructor-prototype.html
Similar Posts
- None Found


































