meow
meow

Reputation: 28164

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!

Upvotes: 12

Views: 2648

Answers (1)

Mark Lutton
Mark Lutton

Reputation: 7007

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;
    }
  };
}

Upvotes: 18

Related Questions