JS :Code convention and Best Practices

JS :Code convention and Best Practices


Javascript code should not be embedded in the html if it is not meant for a single session.
<Script src=sth.js> should be placed as late as possible.
Unit of indentation is four spaces.
Declare variables in the starting of the function. Implied variables should not be used.
All unction should be declared before use.


function outer(c,d) {
   var e = c*d;
   function inner(a,b) {
       return (a*e) + b;
   }
   return(0,1);
}


Anonymous Function:
A function without an identifier.
One space between the function and the left parenthesis.


div.onClick = function (e){}


The use of global function should be minimized.
When the function is invoked immediately it should be covered inside parentheses.
Global variable should all be in CAPS.


The do statement always ends with an semicolon.

Private Members in JAVASCRIPT:
Arrays are objects. Functions are objects.Objects are objects.
Objects are name value pairs. The name are strings and the values are strings, numbers booleans and objects.Objects are implemented as hashtable so the value can be retrieved easily.
If the value is a function then we can consider it as a method.
When a method is invoked the this variable is set to the object.
The method can access the instance variable through this keyword.
Private members are created by constructor.
Ordinary vars and parameters becomes the private members.

Private methods are the inner functions of the constructor.


A privileged method can be used to access the private variable and methods and is itself accessible to the public method and outside.


Privilege method are assigned with “this” keyword in the constructor.


Private and privileged member are only created at constructor. Public members can be added anytime.


PUBLIC:
function constructor() {
   this.membrane =  value;
}


Private:
function constructor(){
   var that =  this;
   var membrane = value;
   function membername(){
       
   }


}


Privilege:
function constructor(){
this.membername = function () {
   }
}


The <script> tag:


It identifies a block of script in the page.
It loads a script file.


Avoid the use of “document.write”. It is recklessly dependent on timing and encourages bad structure in which script and markup are intermingled.

The src attribute is not constrained by the same origin policy.

Comments