Basic JavaScript encoding Mode

Source: Internet
Author: User
1. variable definition // common syntax var a = 0; var B = 1; var c = 'xxx'; // recommended syntax var a = 0, B = 1, c = 'xxx'; 2. try to use the literal. // var obj = new Object (); obj. a = 'a'; obj. B = 'bb'; obj. c = 'cc'; var arr = new Array (); // recommended 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 literal var regex = New RegExp ('someting'); // The constructor var cls = 'someclass 'is used only when the regular expression may change ', regex = new RegExp (cls + '\ s *', 'ig '); // only for dynamic regexs // other cases all use the literal var regex =/someting/ig; 4. set the Default value (personal feeling typeof) // default valuesvar arg = arg | 'default'; // fallback document. getElementById ('test '). onclick = function (event) {var event = event | window. event ;}; function getX (a) {return a + 1 | 'default' ;}< BR> <BR> f Unction getY (B) {<BR> return typeof B! = "Undefined "? B: 'default'; <BR >}5. conditional judgment // Conditionsanswer = obj & obj. xx & obj. xx. xxx; // continuously judge if (obj & obj. xx & obj. xx. xxx) {// do something} if (obj. xx) {// do something} if (! Obj) {// do something} // use full equals to judge if (a = B) {// do something} // try not to detect the browser, only checks whether the feature to be used supports if (document. getElementById) {// ability detect} 6. ternary operator // Ternarycheck? 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;} // format the ternary operator foo = predicate? "One": predicate? "Two": "default"; // format 7. insert iteration value // Insert iterationvar name = value [I]; I ++; // Insert the iteration value directly into var name = value [I ++]; 8. DOM operation // DOM Operationel. style. display = 'none'; // offline // operationel. style. display = 'block'; // use document fragment for better operations: www.2cto.com var fragment = document. createDocumentFragment (); // better el. innerHTML = ''; // fast remove all children, but may leaks memoryel. innerHTML = 'xxx'; // OK, Use it! // Handle NodeListvar images = document. getElementsByTagName ('img ') with caution; // be careful! Dynamic list 9. event proxy // use event proxy to listen to event document on the outer element. 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 Namespacevar MYAPP ={}; MYAPP. dom. get = function (id) {}; MYAPP.style.css = function (el, style) {}; MYAPP. namespace ('event'); 11. chain operation // Chaining operation: return thisfunction 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 Objectfunction 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 // 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. 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 the new Array. forEach (); getElementsByClassName (); querySlectorAll (); // first, check whether new features are supported. if yes, use if (document. getElementsByClassName) {// use} else {// your implementations} 18. inertia loading // only judge once. if you call this function again, you do not need to judge function lazyDef () {if (condition1) {lazyDef = function () {};} else if (condition2) {lazyDef = function () {};} return lazyDef () ;}19. private function and public method var MYAPP ={}; MYAPP. dom = (function () {var _ setStyle = function (el, prop, value) {console. log ('setstyle') ;}; return {setStyle: _ setStyle };}) (); // when MYAPP. dom. when setStyle is accidentally overwritten, _ setStyle is still available internally 20. debug // 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 }}

 

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.