I am in the process of refactoring my code. I'm having trouble deciding on how exactly to implement a couple utility functions I have. Specifically, if certain functions are better off in my personal namespace or extending js Objects directly.
Example of extending native JavaScript Objects
(is this the proper term?).
String.prototype.prettyDate = function(){
return (this.substr(5,2) + '/' + this.substr(8) + '/' + this.substr(0,4));
}
var myString = "2010-12-27";
//logs 12/27/2010
console.log(myString.prettyDate);
Example using my own namespace
var myNamespace = (function(){
var my = {};
my.prettyDate = function ( dateStr ){
return (dateStr.substr(5,2) + '/' + dateStr.substr(8) + '/' + dateStr.substr(0,4));
}
return my;
}());
var pretifiedDate = myNamespace.prettyDate('2010-12-27');
//logs 12/27/2010
console.log(pretifiedDate);
Questions to consider
- When is a utility justifiably inserted into a native JavaScript Object?
- How can I tell when a utility is better off being in my own namespace?
Almost never, because of:
a/ possible conflicts with other libraries
b/ extended functions are iterated as properties by in operator, which poses problems unless filtered out by hasOwnProperty (which is not commonly used)
You can justify this for small, one-script works, but only if you 200% sure that no one, never ever will try to reuse that code somewhere. In such case use it only for functionality which spans more than one module of your code. Extending String with trim() - ok, extending String with prettyDate() - doubtful, extending Object with displayAsPageHeader() - scary.
So, almost always.