Indentation
The unit of indentation is four spaces, not tabs.
Functions
Functions definitions should have one space between the closing parenthesis and opening bracket. Parameters should be separated by one space.
- function sampleFunction(arg1, arg2) {
- alert(‘Hello’);
- }
Classes
Classes should usually be created in the Namespace namespace, to avoid conflicts. Singleton classes should instantiate themselves, and not require external instantiation.
- /**
- * Module Description
- */
- Namespace.MyModule = (function($){
- var that = {};
- /**
- * Sample method
- *
- * @param string arg1
- * @param string arg2
- *
- * @return string
- */
- that.publicMethod = function(arg1, arg2) {
- return ‘foo’;
- }
- return that;
- }(jQuery);
/**
* Sample method
*
* @param string arg1
* @param string arg2
*
* @return string
*/
that.publicMethod = function(arg1, arg2) {
return ‘foo’;
}
return that;
}(jQuery);
Control Structures
Opening braces should be placed on the same line as the structure keywords, with the final closing brace on a new line.
- if (condition == true) {
- // Do something
- } else if (foo == bar) {
- // Do something else
- } else {
- // Do yet another thing
- }
- for (var i = 0; i < 10; i++) {
- var x = i + 1;
- }
- switch(val) {
- case 1:
- alert(1);
- break;
- case 2:
- alert(2);
- break;
- }
for (var i = 0; i < 10; i++) {
var x = i + 1;
}
switch(val) {
case 1:
alert(1);
break;
case 2:
alert(2);
break;
}
jQuery
Since we use both jQuery and prototype, we must use jQuery in no-conflict mode. This means that you cannot reference jQuery by the $ global variable, and instead must use jQuery. For example:
// Incorrect, will not work
$(‘#element’).hide();// Correct
jQuery(‘#element’).hide();
Alternatively, if you are creating a large module or plugin, you can wrap your code in a function, and pass jQuery by reference:
// Anonymous function wrapper
!function($){
// In this context, $ refers to the argument passed to our wrapper function
$(‘#element’).hide();
}(jQuery);