JavaScript Basic Coding Mode Summary _ Basics

Source: Internet
Author: User
Regardless of the coding style, design pattern, etc., the coding style is generally focused on the writing specification, while the design pattern is biased toward the program architecture design. These "patterns" in this article include some common methods or tips for writing JavaScript code, which can help beginners of JavaScript to quickly improve the quality of their code. Of course, before the first to ensure that the standard writing habits, on top of this article can be introduced to the knowledge point of code writing, you can greatly improve the code quality.
The following is the author of some of the points, there is no logical order, where to think where to write, the deficiencies are welcome to add.
1. Variable definition
Copy Code code as follows:

General wording
var a = 0;
var b = 1;
var c = ' xxx ';
Recommended wording
var a = 0,
b = 1,
c = ' xxx ';

2. Use literal quantity as much as possible
Copy Code code as follows:

General wording
var obj = new Object ();
obj.a = ' AA ';
obj.b = ' BB ';
OBJ.C = ' CC ';
var arr = new Array ();
Recommended wording
var obj = {
A: ' AA ',
B: ' BB '
};
var arr = [];
function Getxx (index) {
return [' AA ', ' BB ', ' xx ', #, ' XXB '] (index);
}
function GetMessage (code) {
return {
404: ' xxx ',
: ' xxx '
}[code];
}

3. Regular literal volume
Copy Code code as follows:

var regex = new RegExp (' someting ');
Constructors are used when regular expressions may change
The var cls = ' SomeClass ',
Regex = new RegExp (cls + ' \\s* ', ' IG '); Only for dynamic Regexs
All other cases are used in literal quantities
var regex =/someting/ig;

4. Set Default values
Copy Code code 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 code 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 congruent judgment
if (A = = = B) {
Do something
}
Try not to detect the browser, only detect whether the attribute to be used supports
if (document.getElementById) {
Ability Detect
}

6. Ternary operator
Copy Code code as follows:

Ternary
Check? Value1:value2;
Ternary operators more concise
var foo = (condition)? Value1:value2;
function xx () {
if (condition) {
return value1;
}else{
return value2;
}
}
function xx () {
return (condition)? Value1:value2;
}
Format ternary operator
Foo = predicate? "One":
Predicate? "Two":
"Default"; Format

7. Insert Iteration Value
Copy Code code as follows:

Insert Iteration
var name = Value[i];
i++;
Inserts an iteration value directly into the
var name = value[i++];

8. DOM Operations
Copy Code code as follows:

DOM Operation
El.style.display = ' None '; Offline
Operation
El.style.display = ' block ';
Working with document fragmentation is better
var fragment = Document.createdocumentfragment (); Better
el.innerhtml = '; Fast Remove all children and but may leaks memory
el.innerhtml = ' xxx '; OK, use it!
Be careful with nodelist.
var images = document.getelementsbytagname (' img '); Be careful! Dynamic list

9. Event Agent
Copy Code code as follows:

Using the event agent to listen for events on the more outer elements
document.getElementById (' list '). onclick = function (evt) {
var evt = evt | | Window.event,
target = Evt.target | | Evt.srcelement;
if (target.id = = ' Btn1 ') {
Do something
}
}

10. Namespaces
Copy Code code 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 Type operation
Copy Code code 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 code as follows:

Function
(function () {
var _private = ' cant to me ';
})();
(function ($) {
$ (' #xxb '). Click (function () {});
}) (JQuery);

13. Configuration Objects
Copy Code code as follows:

Configure Object
function foo (ID, conf, null, NULL) {
Do Somethin
}
Foo (' Bar ', {
Key1:1,
Key2:2
});

14. Type Conversion
Copy Code code 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 code as follows:

Used only when forward compatibility is required, others do not recommend extending the prototype object
Array.prototype.forEach = function () {
Only for forward compatible
};

16. Cycle optimization
Copy Code code as follows:

Cache
For (var i=0, j = document.getelementsbytagname (' a '). length; i0; i--) {
Maybe faster
}
It's said to be the fastest.
while (i--) {
Maybe fastest
}

17. To maximize the use of new
Copy Code code as follows:

Array.foreach ();
Getelementsbyclassname ();
Queryslectorall ();
First detect whether to support new features, can be used with
if (document.getelementsbyclassname) {
Use
}else{
Your implementations
}

18. Inert Loading
Copy Code code as follows:

Just once, call the function again without judgment
function Lazydef () {
if (condition1) {
Lazydef = function () {};
}else if (condition2) {
Lazydef = function () {};
}
return Lazydef ();
}

19. Private functions and public methods
Copy Code code as follows:

var MYAPP = {};
Myapp.dom = (function () {
var _setstyle = function (el, prop, value) {
Console.log (' SetStyle ');
};
return {
SetStyle: _setstyle
};
})();
When MYAPP.dom.setStyle is inadvertently overwritten, _setstyle is still available internally

20. Debugging
Copy Code code as follows:

Try to use, you can pass in multiple parameters, the final output of the concatenation of the string
Console.log (' xx ', ' xx ', ' ... ');
Console.dir (Someobj);
Console.dirxml (Somedom);
Console.time (' timer ');
Console.warn (' xxx ');
Encapsulation can ensure that inadvertently released will not cause problems, but the error number may be problematic
function msg (msg) {
If (console && console.log) {
Console.log (msg); Wrong line number
}
}

Basically, this is the only thing that's been thought of, welcome to the discussion:
Related Article

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.