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: //
Var a = 0;
Var B = 1;
Var c = 'xxx ';
// Recommended statement
Var a = 0,
B = 1,
C = 'xxx ';
2. Try to use the literalCopy codeThe Code is as follows: //
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 ExpressionsCopy 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 valueCopy 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 judgmentCopy 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 OperatorsCopy 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 valuesCopy codeThe Code is as follows: // Insert iteration
Var name = value [I];
I ++;
// Insert the iteration value directly
Var name = value [I ++];
8. DOM operationsCopy 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 proxyCopy codeThe Code is as follows: // use the event proxy to listen to 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. namespaceCopy 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 OperationsCopy 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 ScopeCopy codeThe Code is as follows: // Function
(Function (){
Var _ private = 'cant see Me ';
})();
(Function ($ ){
$ ('# Xxb'). click (function (){});
}) (JQuery );
13. Configuration objectCopy codeThe Code is as follows: // Configure Object
Function foo (id, conf, null, null ){
// Do somethin
}
Foo ('bar ',{
Key1: 1,
Key2: 2
});
14. type conversionCopy 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 prototypeCopy 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 OptimizationCopy 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 featureCopy 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 LoadingCopy 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 methodsCopy codeCode: 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. debuggingCopy codeThe Code is as follows: // use it whenever possible. 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 :)