Yansky said:
I'm just starting to learn about the prototype object in javascript
and I was wondering if someone could explain just in laymans terms why
you would use it instead of a regular functions? It seems like it does
the same thing as regular functions except in a more complicated way.
Are you asking about the advantages and disadvantages of object-oriented
constructs w/ method calls vs function calls, or about the use of
prototypes vs putting all properties including methods in the same
object?
Objects provide their own mechanism for property lookup. This means that
different objects can provide methods and properties with the same name
to do different things. In other words, they provide a straight forward
way of doing polymorphism:
myCollectionOfObjects.forEach(function(o) {
o.quack(); // what quack() does is determined by o itself
});
Functions are useful for actions that aren't intimately tied to a single
object and they're easier to use in higher-order constructs - getting
the above construct to work using "pure oo" only would get seriously
ugly very soon, see classic Java's sortable collections for instance.
As for using prototypes vs direct object properties; prototypes can be
shared so they're more efficient if you otherwise need to copy /
initialize a lot of properties. Also, they make it easy to extend
existing "classes of" objects:
this code from the mozilla developer site:
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun, /* thisp */) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this)
fun.call(thisp, this
, i, this);
}
};
}
Joost.