clarkk clarkk - 26 days ago 15
Javascript Question

Integer prototype

how can you make an prototype on an Integer?

Integer.prototype.num = function(dec){
return number_format(this.toString(), dec);
}

Answer

There's no Integer in JavaScript, just Number. You can extend Number in the way you've shown.

There are two camps with regard to extending the built-in types in this way. One camp says it's evil and you must not do it; use a separate function you pass the object into. The other camp says this is exactly why we have prototypes, so that we can extend the functionality of things as we see fit.

If you're in the second camp, there are pitfalls to avoid (but see "The world is changing..." below):

  • Never, ever, ever extend Object.prototype in this way. You'll break a huge amount of code.
  • Be very, very wary of extending Array.prototype, you'll break a fair bit of code.

The reason in both cases is that when you extend a prototype in that way, you create an enumerable property on the prototype. That means it shows up in for..in loops. Custom and practice in the JavaScript world is that there must be no enumerable properties on a blank object ({}). Arrays may be more acceptable, but beware people who don't really understand what for..in does who think it will loop through the array indexes; if you extend Array.prototype in this way, you'll break their loops. (I would argue their loops were already broken, but leave that to the side...)

The world is changing, though, because ECMAScript5 gave us a way to add non-enumerable properties to objects, and all vaguely up-to-date browsers implement it. It's called Object.defineProperty:

Object.defineProperty(Number.prototype, "num", {
    enumerable: false,
    value: function() { ... }
});

Note that enumerable: false (false is the default for enumerable; I'm being explicit here for emphasis). That means it doesn't show up on for..in loops, and so softens that argument against extending prototypes of native objects.

However, the possibility of naming conflicts (with other code also extending the prototype, or features added in future versions of JavaScript) remains, even with Object.defineProperty.

Comments