Basic JavaScript encoding Mode

Source: Internet
Author: User

1. variable definition
// General statement
Var a = 0;
Var B = 1;
Var c = 'xxx ';
 
// Recommended statement
Var a = 0,
B = 1,
C = 'xxx ';
 
2. Try to use the literal

// General statement
Var obj = new Object ();
Obj. a = 'a ';
Obj. B = 'bb ';
Obj. c = 'cc ';
 
Var arr = new Array ();
 
// Recommended statement
Var obj = {
A: 'A ',
B: 'bb'
};
 
Var arr = [];
 
Function getXX (index ){
Return ['A', 'bb ', 'XX', 55, 'xxb'] (index );
}
 
Function getMessage (code ){
Return {
404: 'xxx ',
500: 'xxx'
} [Code];
}
  
3. Regular Expressions

Var regex = new RegExp ('someting ');
 
// Use the constructor only when the regular expression may change
Var cls = 'someclass ',
Regex = new RegExp (cls + '\ s *', 'ig '); // only for dynamic regexs
 
// Use the literal in other cases
Var regex =/someting/ig;
  
4. Set the default value (personal feeling typeof)

// Default values
Var arg = arg | 'default'; // fallback
 
Document. getElementById ('test'). onclick = function (event ){
Var event = event | window. event;
};
 
Function getX (){
Return a + 1 | 'default ';
} <BR> function getY (B) {<BR> return typeof B! = "Undefined "? B: 'default'; <BR>}
 
5. Condition judgment

// Conditions
Answer = obj & obj. xx & obj. xx. xxx;
 
// Continuous judgment
If (obj & obj. xx & obj. xx. xxx ){
// Do something
}
 
If (obj. xx ){
// Do something
}
 
If (! Obj ){
// Do something
}
 
// Use full-level judgment
If (a = B ){
// Do something
}
 
// Try not to check the browser. Only check whether the features to be used are supported.
If (document. getElementById ){
// Ability detect
}
  
6. Ternary Operators

// Ternary
Check? Value1: value2;
 
// The ternary operators are more concise.
Var foo = (condition )? Value1: value2;
 
Function xx (){
If (condition ){
Return value1;
} Else {
Return value2;
}
}
 
Function xx (){
Return (condition )? Value1: value2;
}
 
// Format the ternary Operator
Foo = predicate? "One ":
Predicate? "Two ":
"Default"; // format
  
7. Insert iteration values

// Insert iteration
Var name = value [I];
I ++;
 
// Insert the iteration value directly
Var name = value [I ++];
  
8. DOM operations

// DOM Operation
El. style. display = 'none'; // offline
// Operation
El. style. display = 'block ';
 
// Use the document fragment to perform better operations on www.2cto.com
Var fragment = document. createDocumentFragment (); // better
 
El. innerHTML = ''; // fast remove all children, but may leaks memory
El. innerHTML = 'xxx'; // OK, use it!
 
// Handle NodeList with caution
Var images = document. getElementsByTagName ('img '); // be careful! Dynamic list
  
9. Event proxy

// Use event proxy to listen for events on the outer Element
Document. getElementById ('LIST'). onclick = function (evt ){
Var evt = evt | window. event,
Target = evt.tar get | evt. srcElement;
 
If (target. id = 'dn1 '){
// Do something
}
}
  
10. namespace

// An Object as a Namespace
Var MYAPP = {};
MYAPP. dom. get = function (id ){};
MYAPP.style.css = function (el, style ){};
 
MYAPP. namespace ('event ');
  
11. Chain Operations

// Chaining operation: return this
Function setValue (el, value ){
El. value = value;
Return this;
}
 
Var obj = new MYAPP. dom. Element ('span ');
Obj. setText ('hello ')
. SetStyle ('color', 'red ')
. SetStyle ('font', 'verdana ');
  
12. Private Scope

// Function
(Function (){
Var _ private = 'cant see Me ';
 
})();
 
(Function ($ ){
$ ('# Xxb'). click (function (){});
}) (JQuery );
  
13. Configuration object

// Configure Object
Function foo (id, conf, null, null ){
// Do somethin
}
 
Foo ('bar ',{
Key1: 1,
Key2: 2
});
  
14. type conversion

// Type Conversion
+ '010 '= 10;
Number ('010 ') = 10;
ParseInt ('010 ', 10) = 10;
10 + ''= '10 ';
 
+ New Date () // timestamp
+ New Date;
  
15. Extended prototype

// It is used only when forward compatibility is required. In other cases, it is not recommended to extend the prototype object.
Array. prototype. forEach = function (){
// Only for forward compatible
};
  
16. Cyclic Optimization

// Cache
For (var I = 0, j = document. getElementsByTagName ('A'). length; i0; I --){
// Maybe faster
}
 
// It is said to be the fastest
While (I --){
// Maybe fastest
}
  
17. Try to use the new feature

Array. forEach ();
GetElementsByClassName ();
QuerySlectorAll ();
 
// First, check whether new features are supported.
If (document. getElementsByClassName ){
// Use
} Else {
// Your implementations
}
  
18. inert Loading

// Only judge once. You do not need to judge if you call this function again
Function lazyDef (){
If (condition1 ){
LazyDef = function (){};
} Else if (condition2 ){
LazyDef = function (){};
}
Return lazyDef ();
}
  
19. Private functions and public methods

Var MYAPP = {};
 
MYAPP. dom = (function (){
Var _ setStyle = function (el, prop, value ){
Console. log ('setstyle ');
};
 
Return {
SetStyle: _ setStyle
};
})();
 
// When MYAPP. dom. setStyle is accidentally overwritten, _ setStyle is still available internally
  
20. debugging

// Try to use it. You can input multiple parameters and output the concatenated string.
Console. log ('XX', 'XX ','...');
Console. dir (someObj );
Console. dirxml (someDom );
Console. time ('timer ');
Console. warn ('xxx ');
 
// Encapsulation ensures that accidental release will not cause problems, but the row number may be faulty when an error is reported.
Function msg (msg ){
If (console & console. log ){
Console. log (msg); // wrong line number
}
}

 

 

From z s k

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.