System Analyst and PHP Developer working in Kingdom of Saudi Arabia
Yesterday while finishing the XLS generated report in one of the application I’m involved with, I came across some JS files within the script folder that is like 2007 or so coded and upon checking…the code is a real ugly beast!!!
Why? all functions were defined as global objects or within the window object and funny thing is that even the built-in function confirm() were override with their functionality! I believe the original programmer who wrote it assumes that throughout its code existence, no other developer/programmer would use similar or related function..which is really not a very good approach.
Example:
common.js
function removeData(el) {
var tmp = $(el);
$(tmp).text("").attr("background-color","white");
};
…function list and so on.There are around 14 attached JS files which had functions scattered randomly and were were just renamed function like removeDataY() which has the same functionality.Sigh…
Anyway, for those who are new to javascript…I’d suggest you encapsulate or create a simple namespace for your code so that it would not conflict with other external JS file assuming the function used is the same.
Example:
common1.js
var CM1 = {};
CM1.removeData = function(el) {
var tmp = $(el);
$(tmp).text("").attr("background-color","white");
};
…function list and so on.
common2.js
var CM2 = {};
CM2.removeData = function(el) {
var tmp = $(el);
$(tmp).text("").attr("background-color","white");
};
And within application code, CM1.removeData() will never have conflict with CM2.removeData() since they belong to a different object, it’s cleaner and can easily be debug…There are some pattern which I find useful like the “Module Pattern” from Yahoo but that’s a different story and I’ll post it later in the next blog entry.