Over time and thousands of lines of professional Javascript programming, I’ve developed an almost bulletproof Javascript layout style. It is important to have one, even if you are the only person working on your script, because:
- it helps you read the code more quickly
- it helps you not forget browser "gotchas"
- it makes your code more reusable from project to project
My style rules
- All functions and variables should live in their own namespace, not polluting the base context as much as possible. In other words, I never write simple “function foo(arg) { … };”, since that might conflict with other libraries implementations of "foo." Instead I always start every javascript source file by declaring my root namespace. I use "SSS" as the root, like so: "var SSS = SSS || {};"
- Always put related functions together in their own namespace. For example, on a recent project codenamed "scr", I have three namespaces: SSS.scr, SSS.util and SSS.layout. This allows me to reuse useful and debugged code on different projects.
- I put module-level variables at the top of the module namespace, then alphabetize all other functions.
- I put a final declaration at the end of the array, "ZZZ : ‘do not remove’", which keeps me from making the IE and Safari deadly mistake of having a trailing comma at the end of the last function.
An example javascript file using my style
var SSS = SSS || {};
SSS.scr = {
active : 'switch-0',
flag : false,
initialized : false,
log : false,
update_depth : 0,
add_delimited_field : function(field, count, delimiter, defval) {
// example
},
calc_price : function() {
// example
},
cents_to_dollars : function(val) {
// I like this simple function, so I left it in.
var d = Math.floor(val/100);
var c = val % 100;
if (c < 10) c = "0" + c;
return d + '.' + c;
},
cleanup_names : function(adults, children, total) {
// example
},
init : function() {
// init stuff here
SSS.scr.initialized = true;
},
ZZZ : "do not delete"
}
// jquery onload initializer
$(function() {
SSS.scr.init();
});
Technorati Tags: javascript, style
















0 responses so far ↓
There are no comments yet...Kick things off by filling out the form below.
Leave a Comment