Home > Web Front-end > JS Tutorial > body text

Summary of basic JavaScript coding patterns_basic knowledge

WBOY
Release: 2016-05-16 17:53:21
Original
1005 people have browsed it

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

Copy code The code is as follows:

//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
Copy code The code is as follows:

//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
Copy code The code is as follows:

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
Copy code The code is as follows:

// 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
Copy code The 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 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
Copy code The code is as follows:

// 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
Copy code The code is as follows:

// Insert iteration
var name = value[i] ;
i ;
// Directly insert the iteration value into
var name = value[i ];

8. DOM operation
Copy code The code is as follows:

// 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
Copy code The code is as follows:

// 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
Copy code The 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 operation
Copy code The 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 code The code is as follows:

// Function
(function(){
var _private = 'cant see me';
})();
(function($){
$('#xxb').click(function( ){ });
})(jQuery);

13. Configuration object
Copy code The code is as follows:

// Configure Object
function foo(id, conf, null , null){
// do somethin
}
foo( 'bar', {
key1 : 1,
key2 : 2
});

14. Type conversion
Copy code The 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 code The code is as follows:

// 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
Copy code The 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 new special new
Copy code The code is as follows:

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
Copy code The code is as follows:

// 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
Copy code The 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 code The code is as follows:

// 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 :)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template