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?