Click to See Complete Forum and Search --> : When to use Prototypes and Classes?


hnorris
02-06-2003, 05:05 PM
Hi -

If I want to dynamically create a huge number of elements in my page for which I need to add methods and properties, is there any efficiency or memory optimization advantage to using prototypes, and if so, how would they be used?? For example, here's how I typically would dynamically create such an element:
//---------------------------------
function createDiv() {
var d = document.createElement("DIV");
d.name = "testDiv";
d.innerHTML = "foo";
d.onmouseover = over;
return d;
}
//----------------------------
function over() {
alert("Over div");
}
// DO THIS ON ONLOAD
for(var i=0; i< 1000; i++) {
document.body.appendChild( createDiv() );
}

I know that on Mozilla you can prototype the HTMLElement or its subinterfaces, etc. but on IE how would I do this, or would I really gain anything by doing so? Also, is it possible to extend a function using prototypes? It would be great to find a good reference, book or web site, that explains JS OO and classes in a more Java/C++ familiar style. Thanks for any help you can offer on this!!

- Hnorris

Dan Drillich
02-08-2003, 12:08 PM
“JavaScript The definitive Guide” says –

Prototypes and Inheritance
We’ve seen how inefficient it can be to use a constructor to assign methods to the objects it initializes. When we do this, each and every object created by the constructor has identical copies of the same method properties. There is a much more efficient way to specify methods, constants and other properties that are shared by all objects in a class.
JavaScript objects “inherit” properties from a prototype object (Prototypes were introduced in JavaScript 1.1; they are not supported in the now obsolete JavaScript 1.0). Every object has a prototype; all of the properties of the prototype appear to be properties of any objects for which it is a prototype. That is, each object inherits properties from its prototype.
The prototype of an object is defined by the constructor function that was used to create initialize the object. All functions in JavaScript have a prototype property that refers to an object. This prototype object is initially empty, but any properties you define in it will be inherited by all objects created by the constructor.
A constructor defines a class of objects and initializes properties, such as width and height, that are the state variables for the class. The prototype object is associated with the constructor, so each member of the class inherits exactly the same set of properties from the prototype. This means that the prototype is an ideal place for methods and other constant properties.


So, I think the above answers your question – using the prototype object is useful when multiple objects are created for the same class.

Cheers,
Dan