Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

javascript - Integer prototype

how can you make an prototype on an Integer?

Integer.prototype.num = function(dec){
    return number_format(this.toString(), dec);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...