Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are practical use cases of javascript prototype objects?

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!

like image 557
meow Avatar asked Sep 13 '10 17:09

meow


1 Answers

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;
    }
  };
}
like image 195
Mark Lutton Avatar answered Oct 21 '22 16:10

Mark Lutton