No matter how you write a program, you will be exposed to the coding style, design patterns, and other concepts. The encoding style is generally focused on writing specifications, while the design pattern is biased towards programming architecture design. The "Patterns" I have compiled in this article include some common methods or tips for writing JavaScript code, which can help beginners who are new to JavaScript to quickly improve the code quality. Of course, before that, we must first ensure the standard writing habits. On this basis, we can apply the knowledge points introduced in this article to code writing, which can greatly improve the code quality.
The following are some of my points. There is no logic order, and I want to write where I want to go. I would like to add some points to my point.
1. variable definition
Copy codeThe Code is as follows:
// 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
Copy codeThe Code is as follows:
// 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
Copy codeThe Code is as follows:
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
Copy codeThe Code is as follows:
// Default values
Var arg = arg | 'default'; // fallback
Document. getElementById ('test'). onclick = function (event ){
Var event = event | window. event;
};
Function getX (){
Return a + 1 | 'default ';
}
5. Condition judgment
Copy codeThe Code is as follows:
// 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
Copy codeThe Code is as follows:
// 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
Copy codeThe Code is as follows:
// Insert iteration
Var name = value [I];
I ++;
// Insert the iteration value directly
Var name = value [I ++];
8. DOM operations
Copy codeThe Code is as follows:
// DOM Operation
El. style. display = 'none'; // offline
// Operation
El. style. display = 'block ';
// Use document fragments for better operations
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
Copy codeThe Code is as follows:
// 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
Copy codeThe Code is as follows:
// An Object as a Namespace
Var MYAPP = {};
MYAPP. dom. get = function (id ){};
MYAPP.style.css = function (el, style ){};
MYAPP. namespace ('event ');
11. Chain Operations
Copy codeThe Code is as follows:
// 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
Copy codeThe Code is as follows:
// Function
(Function (){
Var _ private = 'cant see Me ';
})();
(Function ($ ){
$ ('# Xxb'). click (function (){});
}) (JQuery );
13. Configuration object
Copy codeThe Code is as follows:
// Configure Object
Function foo (id, conf, null, null ){
// Do somethin
}
Foo ('bar ',{
Key1: 1,
Key2: 2
});
14. type conversion
Copy codeThe Code is as follows:
// Type Conversion
+ '010 '= 10;
Number ('010 ') = 10;
ParseInt ('010 ', 10) = 10;
10 + ''= '10 ';
+ New Date () // timestamp
+ New Date;
15. Extended prototype
Copy codeThe Code is as follows:
// 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
Copy codeThe Code is as follows:
// 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
Copy codeThe Code is as follows:
Array. forEach ();
GetElementsByClassName ();
QuerySlectorAll ();
// First, check whether new features are supported.
If (document. getElementsByClassName ){
// Use
} Else {
// Your implementations
}
18. inert Loading
Copy codeThe Code is as follows:
// 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
Copy codeThe Code is as follows:
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
Copy codeThe Code is as follows:
// 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
}
}
This is basically the only thing that comes to mind at the moment. You are welcome to discuss it further :)