views:

62

answers:

1

How are you using javascript prototype objects in your everyday code? I found it hard to either explain or find use cases for it.

Purpose driven examples and pseudo code examples would be great - thanks!

+6  A: 

Here is a very simple example. Wouldn't be nice if String had a trim() function so you could do this?

var x = "   A B C  ";
var y = x.trim();  // y == "A B C"

Well, it can. Just put this at the beginning of your code:

if (!String.prototype.trim) {
  String.prototype.trim = function() {
    try {
      return this.replace(/^\s+|\s+$/g, "");
    } catch (e) {
      return this;
    }
  };
}
Mark Lutton
I guess this is a good answer but every time you define a function you are using the Function prototype object.
ChaosPandion
@ChaosPandion, And every time you create an object (including a function) you're using the Object object...
strager
It's a good example, but I can't think of any use for the try/catch block. If a reg exp literal will throw an error, so will the try keyword.
kennebec
I agree with @kennebec; why would the call throw?
strager
Great answer! Now i immediately see how this is useful. Do you have another example, where you are using your own class (as opposed to the String class), or where you are applying inheritance?
ming yeow
Not in pure JavaScript. I use the Dojo Toolkit, which gives you syntactic sugar so that it looks like you are defining classes like in C++ or Java (with multiple inheritance). I wrote an Ajax class with functions get, put, post, delete. Then I wrote a subclass of this (AppClient) with domain-specific functions. Behind the scenes the class definitions were really prototypes. I create an AppClient object appClient. If I call appClient.get() it looks in the object, then in the AppClient prototype, then in the Ajax prototype for the function get().
Mark Lutton
@strager and kennebec, try / catch is just a habit, like fastening my seat belt even though I know I'm going to drive carefully and not get into an accident. And I KNOW I'm not going to type anything like "return this.replace(/^s+g, "");" I NEVER make misteaks like that.
Mark Lutton