|
|
(24 intermediate revisions by 7 users not shown) |
Line 1: |
Line 1: |
| ==Javascript coding guidelines==
| | See [http://developer.mozilla.org/en/docs/JavaScript_style_guide JavaScript style guide] at developer.mozilla.org. |
| Here is a list of conventions ([http://forums.mozillazine.org/viewtopic.php?t=129485 discuss]). Some people disagree, but some think it's a good idea to follow them.
| |
|
| |
|
| ===Naming Convensions===
| | [[Category:Redirects]] |
| There are six basic rules.
| |
| | |
| <ol>
| |
| <li>Every variable object name's 1st char should be a lower case.
| |
| var myName = "Torisugari";</li>
| |
| | |
| <li>Every constant object name should be upper cases.
| |
| const MY_NAME = "Torisugari";</li>
| |
| | |
| <li>Every constructor name's 1st char should be an upper case.
| |
| <pre> function Mozillazine(){
| |
| this.description="A Cool Site";
| |
| this.name="mozillaZine";
| |
| this.url="http://www.mozillazine.org/";
| |
| }
| |
| var gMyFav = new Mozillazine();
| |
| </pre></li>
| |
| | |
| <li>By prefix g the author means that is a global object, and unique in the window.
| |
| Exception: A global function doesn't have to start with g.</li>
| |
| <li>By prefix a the author means that is an argument.</li>
| |
| <li>By prefix _ the author means that is a private member.</li>
| |
| </ol>
| |
| | |
| Bad examples, though gramatically correct (see next section for a good example):
| |
| <pre>var bar=0; /*bar should be gBar*/
| |
| function foo(){
| |
| var gFoobar = 0; /* gFoobar is not a global value */
| |
| return gFoobar;
| |
| }</pre>
| |
| | |
| | |
| <pre>function foo(bar){ /* bar should be aBar */
| |
| var aFoobar="foo" + bar; /* aFoobar is not an argument */
| |
| return aFoobar;
| |
| }</pre>
| |
| | |
| | |
| <pre>var gFoo={
| |
| _bar:0
| |
| }
| |
| | |
| var foobar=gFoo._bar; /* _bar is a public member ? */
| |
| /* In other words, you can write only "this._bar" */
| |
| </pre>
| |
| | |
| | |
| ===Avoiding name collisions===
| |
| In order to avoid name collisions, use an unique prefix (for example, name of the extension) for identifiers in overlays (this also applies to XUL '''id'''s in overlays).
| |
| | |
| To avoid prefixing each identifier, you can put them inside an object with unique name:
| |
| <pre>var ExtensionName = {
| |
| _privateMember: 3,
| |
| anotherMember: "A string",
| |
| | |
| init: function() {
| |
| this.doSomething(this.anotherMember);
| |
| },
| |
| | |
| doSomething(): function(aParam) {
| |
| alert(aParam);
| |
| }
| |
| };</pre>
| |
| | |
| ===Miscellaneous===
| |
| [[Dev : Javascript variables]] | |