[I've also written the short answer (for advanced javascripters)]

Javascript is using prototypes and is the only language I know that is doing it. What is the idea behind it? Simple. With prototypes, you can extend (add methods/properties) any class you want anywhere you want anytime you want even if you are not the owner of that object. Object-oriented purist will be shocked but I am more than pleased with that.

Why using prototypes?

It's memory-friendly By adding a method to a class prototype, you are creating a single occurence of the function that is referenced by every objects of that type. It's easy To add a method to a class, no need to create a new class. Juste write TheClass.prototype.theMethod = function() {//code here} and it's done.

It's fun! Maybe not as fun as drinking kool-aid but compared to the complexivity of other languages, we have a champ.

How to use prototypes

Simple. Write the [NameOfTheClass].prototype.[NameOfTheExtension].

You want to add a trim function to the String object? (thanks Greg for the correction)

[source:javascript] String.prototype.trim = function() { return this.replace(/^\s|\s$/g, “”); } [/source]

You want to add an oldValue property to the string

String.prototype.oldValue = “the old value”;

Beware! All the new String objects and the one already declared will have a property with the value “the old value” inside. I can't think of a particular reason why one would do this. If you have one, please comment.

comments powered by Disqus