This document describes the JavaScript style for the Greasemonkey project. Below, use of the word "should" is only for its effect on the prose, and actually means "must".
This guide is based on a Mozilla JavaScript Style Guide document which no longer exists (and was previously the Greasemonkey style guide), which in turn was based on a document by Niel Rashbrook.
if (dlmgrWindow) { dlmgrWindow.focus(); } else { dlmgr.open(window, null); }
compMgr.registerFactoryLocation(CID, CLASSNAME, CONTRACTID, fileSpec, location, type);Bad:
compMgr.registerFactoryLocation(CID, CLASSNAME, CONTRACTID, fileSpec, location, type);Good:
compMgr.registerFactoryLocation( CID, CLASSNAME, CONTRACTID, fileSpec, location, type);
function valueObject(aValue) { return { value: aValue }; }
if (stack.filename != null && stack.filename != gmSvcFilename && stack.filename.substr(0, 6) != "chrome" ) { // ... } var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"] .getService(Ci.mozIJSSubScriptLoader);
var offlineObserver = { observe: function OO_observe(aSubject, aTopic, aState) { if (aTopic == "network:offline-status-changed") setOfflineUI(aState == "offline"); } };This helps with a number of editing and debugging tools.
UPPER_CASE
.GM_
name prefix.g
, e.g. gFormatToolbar
.a
._
, e.g. _internalFunction
. They should not be accessed except by the class they are a member of.return;
with return value;
[value1, value2]
to create a JavaScript array in preference to using new Array(value1, value2)
.{ member: value, ... }
to create a JavaScript object; over new Object()
.true
or false
. For example, write if (ioService.offline)
. Compare objects to null
, numbers to 0
or strings to ""
if there is chance for confusion.These guidelines are not hard and fast rules, but almost always a good idea. Please try to follow them.
while (node = node.parentNode) { /* ... */ }or
for (var i=0, item; item=array[i]; i++) { /* ... */ }This can be a common source of subtle bugs.
switch
statement's case
contains a body, and intentionally falls through to the next (with no break
), add a comment like // fall-through
to make it clear that this is intended.eval()
or equivalents if there is any other possible way to accomplish the goal.setTimeout()
or equivalents with string parameters, only function references. Generally avoid setTimeout()
if at all possible — if not, comment why it was used.