Read Uncle Tom's in-depth understanding of the JavaScript series. Write high-quality code

Source: Internet
Author: User
Tags hasownproperty

feel the uncle's blog is really very good I intend to strict requirements of their own according to the uncle said, so I will be more normative, more thinking to work to write code (a code deep like the sea) 1, as little as possible with the global variables (polluting the global space, and other people's code conflict caused serious consequences)----> Namespace mode or function is automatically executed immediately. 2. The variable is always declared with Var, whether or not within the function, for example:function sum (x, y) {result = x + y;//Create an implicit global variable herereturn result;} 3. Avoid implicit variables such as variables that are not declared by Var in a function, or variables that are not declared. (partial var declaration for example)function foo () {var a = b = 0;//Here A is a local variable, but B is a global variable}just like var a = (b = 0); This line of codePS:(1) The global variables created by Var cannot be deleted;(2) Implicit all variables created without var can be deletedvar global_var1 = 1;global_var2 = 2;delete global_var1;//falseDelete Global_var2;//true4. It is good practice to declare a variable whether it is a local variable or a global variable using a chain assignment, for examplevar a, b; (Variable declaration as VAR and variable name empty)--->5. Top parsing/Pre-parsing of variables in functions such as:function () {alert (name);//undefined instead of an error because our name variable has been parsed just not yet assigned to the expression so his value is undefinedvar name = ' zero ';}PS: The best way to do this is to declare all the variables you need in advance and to assign the expression when the value is determined. 6.for Cycle For (var i = 0;i<myarray.length; i++) {//Do something this is not a good cycle (each cycle is going to read the length of the myarray if MyArray is an HTMLCollection object)// HTMLCollections refers to the object returned by the DOM method, for example:Document.getelementsbyname ()
Document.getelementsbyclassname ()//document.getelementsbytagname ()//Every query is checked dom in real time (Operation Dom is expensive) }The optimization scheme is as follows:(1) for (var i = 0, max = myarray.length; i < Max; i++) {
Use Myarray[i] to do something}(2)for (var i = 0, max = myarray.length; i < Max; i+=1) {//Use myarray[i] to do something}(3) var i, myarray = [];
for (i = myarray.length; i–-;) {
Use Myarray[i] to do something} 5. The for-in loop should also be called "enumeration" on the traversal of non-array objects  6. hasOwnProperty() Method----> filter out the attributes from the prototype chain such as: var man = {
Hands:2,
Legs:2,
Heads:1
};

object.prototype.name= ' zero ';//console.log (man.name);//zero added a name attribute to the prototype and assigned a value of zero for (var i in man) {
if (Man.hasownproperty (i)) {//filter
Console.log (i, ":", Man[i]);
}}the console prints the result asHands:2Legs:2heads:1(the attributes added in the prototype have been filtered out) another form of use hasOwnProperty() is to cancel the method on the Object.prototype. Like this: For (var i in man) {
if (Object.prototype.hasOwnProperty.call (man, i)) {//filter
Console.log (i, ":", Man[i]);
}} the benefit is to avoid naming conflicts when the man object is redefined hasownproperty. Also avoids all methods of long attribute lookup objects, you can "cache" it using local variables.  var i, Hasown = Object.prototype.hasOwnProperty;
For (I in Mans) {
if (Hasown.call (man, i)) {//filter
Console.log (i, ":", Man[i]);
}} PS: It is best not to add built-in prototypes.  7. Avoid implicit type conversions-----> Always use the = = = and!== operators 8. Avoid eval (); This method accepts arbitrary strings and treats them as JavaScript code, for example:Reverse Example
var property = "Name";
Alert (eval ("obj." + property));

better.
var property = "Name";
Alert (Obj[property]);  9. Do not pass strings to the SetInterval (), SetTimeout (), and function () constructors-----> Transfer Function Reverse Example
SetTimeout ("MyFunc ()", 1000);
SetTimeout ("MyFunc (1, 2, 3)", 1000);

better.
SetTimeout (MyFunc, 1000);
SetTimeout (function () {
MyFunc (1, 2, 3);
}, +);  using function instead of Eval is a good choice. var jsstring = "var un = 1; Console.log (un); ";
eval (jsstring); Logs "1"

jsstring = "var deux = 2; Console.log (deux); ";
New Function (jsstring) (); Logs "2"

jsstring = "var trois = 3; Console.log (trois); ";
(function () {
eval (jsstring);
}()); Logs "3"

Console.log (typeof un); Number
Console.log (typeof deux); "Undefined"
Console.log (typeof trois); "Undefined" If you absolutely must use eval (), you might consider using the new Function () instead. There is a small potential benefit because the code evaluation in the new function () is run in the scope of the local functionthe eval () differs from the function construct in that eval () interferes with the scope chain, while function () is more in line with the following example:  (function () {
var local = 1;
Eval ("local = 3; Console.log (local) "); Logs "3"
Console.log (local); Logs "3"
}());

(function () {
var local = 1;
Function ("Console.log (typeof local);") (); Logs undefined }()); Numeric conversions under 10.parseInt () the method accepts another cardinality parameter, which is often omitted, but should not be----> in order to avoid conflicting and unexpected results, always specify the cardinality parameter The 11.parseInt () substitution method converts a string into a number, including:+ "08"//result is 8Number ("")//8 12. The code must be indented how many tabs to indent specifically? Two tab? Or a space? To perform according to the team's specifications 13. Curly braces must not be omitted even if you have only one statement in the curly braces-----> always put the previous statement on the same line:  function func () {
return {
Name: "Batman"
};} 14. Use of spaces  var d = 0,
A = B + 1;
if (a && b && c) {
D = a% C;
A + = D; } 15. Write the constructor in uppercase:var adam = new Person (); 16. Constructors--Hump (Camel) naming method:as MyConstructor() 17. For function and method names, variables can also use the small hump-type nomenclature calculateArea() and getFirstName() .  18. Capitalize all the words;var PI = 3.14, 19. It is easier to use an underscore prefix to represent a private property or method20. You need to comment on your code at any time I believe a good programmer will add their own annotations to each function module, not for the sake of others . 

Read Uncle Tom's in-depth understanding of the JavaScript series. Write high-quality code

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.