Jump to content

Dynamic Prototyping


quangthang2004

Recommended Posts

Dear All, The first thing to say thanks all for taking a look on my topic.I have been learning JS for a half a month. During the time for making curiosity about JS. I suddently faced one thing was called Dynamic Prototype. I am wondering what is it for and how to use this. I will get example from my book to illustrate for what I have been dull so far.-----------------------------------------------------------function Car(sColor, iDoors, iMpg) { this.color = sColor; this.doors = iDoors; this.mpg = iMpg; this.drivers = new Array("Mike", "Sue"); if (typeof Car._initialized == "undefined") { Car.prototype.showColor = function () { alert(this.color); } Car._initialized = true; }}------------------------------------------------------------the above code is considered to create Car within color, door , mpg = mile per gallon.the things I have not understood is "_initialized" and the statement in IF condition. I mean the statement , not the content in curly bracket. finally, Please let me know what does Dynamic Prototype use for.Thanks in advance

Link to comment
Share on other sites

It means that the showColor method will only be created after a Car object has been created using the new operator. _initialized is a static variable, which basically means it's global. If one object changes a static variable, the change is there for whenever any other Car object tries to read it.

Link to comment
Share on other sites

It's testing for a property of the Car object. If it doesn't exisit, it dynamically creates a showColor function that alerts the color of the car, and then sets that same undefined property to true so that if statement can't be run again. This would all happen when the Car function/psuedo class is executed/instantiated.

Link to comment
Share on other sites

thanks all.but please let me know why we use Dynamic Prototype.as the above code, we can rewrite the following code---------------------------------------------------------------function Car(sColor, iDoors, iMpg) {this.color = sColor;this.doors = iDoors;this.mpg = iMpg;this.drivers = new Array("Mike", "Sue");Car.prototype.showColor = function () {alert(this.color);}}--------------------------------------------------Sorry if I donot understand all your comment

Link to comment
Share on other sites

I don't see a paticular reason to use "Dynamic Prototyping." The example shows that it is possible, but I don't see any good reason to use it. The prototype allows you to add properties and methods to all existing objects of a particular class.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...