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-friendlyBy 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?
[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.
0 comments:
Post a Comment