No matter you write any program, you will come into contact with concepts such as coding style and design patterns. Coding style generally focuses on writing specifications, while design patterns tend to focus on program architecture design. The "patterns" compiled by the author in this article include some commonly used methods or tips when writing JavaScript code, which can help students who are new to JavaScript quickly improve the quality of their code. Of course, before that, you must first ensure standardized writing habits. On top of that, you can apply the knowledge points introduced in this article to code writing, which can greatly improve the code quality.
The following are some points compiled by the author. There is no logical order. I wrote them wherever I thought. If there are any deficiencies, you are welcome to add and correct me.
1. Variable definition
//General writing method
var a = 0;
var b = 1;
var c = 'xxx';
// Recommended writing
var a = 0,
b = 1,
c = 'xxx';
2. Try to use literals
//General writing
var obj = new Object();
obj.a = 'aa';
obj.b = 'bb';
obj .c = 'cc';
var arr = new Array();
// Recommended writing
var obj = {
a: 'aa',
b: 'bb'
};
var arr = [];
function getXX(index){
return ['aa', 'bb', 'xx', 55, 'xxb'](index);
}
function getMessage(code){
return {
404: 'xxx',
500: 'xxx'
}[code];
}
3. Regular literal
var regex = new RegExp('someting');
// Only use the constructor when the regular expression may change
var cls = 'someclass',
regex = new RegExp(cls '\s*', 'ig'); // only for dynamic regexs
// Use literals in other cases
var regex = /someting/ig;
4. Set default value
// Default values
var arg = arg || 'default '; // fallback
document.getElementById('test').onclick = function(event){
var event = event || window.event;
};
function getX(a) {
return a 1 || 'default';
}
5. Conditional 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 congruence judgment
if(a === b){
// do something
}
// Try not to detect the browser, only detect whether the feature to be used is supported
if(document.getElementById){
// ability detect
}
6. Ternary Operator
// Ternary
check ? value1 : value2;
// The ternary operator is more concise
var foo = (condition) ? value1 : value2;
function xx(){
if(condition){
return value1;
}else{
return value2;
}
}
function xx(){
return (condition) ? value1 : value2;
}
// Formatting Ternary operator
foo = predicate ? "one" :
predicate ? "two" :
"default"; // format
7. Insert iteration value
// Insert iteration
var name = value[i] ;
i ;
// Directly insert the iteration value into
var name = value[i ];
8. DOM operation
// DOM Operation
el.style.display = 'none'; // offline
// operation
el.style.display = 'block';
// Better to use document fragmentation
var fragment = document.createDocumentFragment(); // better
el.innerHTML = ''; // fast remove all children, but may leaks memory
el.innerHTML = ' xxx'; // ok, use it!
// Handle NodeList with care
var images = document.getElementsByTagName('img'); // be careful! dynamic list
9 . Event proxy
// Use event proxy, in more details Listen for events on the elements of the layer
document.getElementById('list').onclick = function(evt){
var evt = evt || window.event,
target = evt.target || evt. srcElement;
if(target.id === 'btn1'){
// 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 operation
// 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
// Only used 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. Loop 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 new special new
Array.forEach();
getElementsByClassName();
querySlectorAll();
/ / First check whether the new feature is supported. If it can be used, use
if(document.getElementsByClassName){
// use
}else{
// your implementations
}
18. Lazy loading
// Only judge once, no judgment is needed when calling the 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 as much as possible, you can pass in multiple parameters, and finally output the spliced String
console.log('xx','xx','...');
console.dir(someObj);
console.dirxml(someDom);
console.time ('timer');
console.warn('xxx');
// Encapsulation can ensure that accidental release will not cause problems, but there may be problems with the line number when reporting errors
function msg( msg){
if(console && console.log){
console.log(msg); // wrong line number
}
}
Basically currently These are the only things that come to mind, welcome everyone to add to the discussion :)