How to write a canonical JavaScript code

Source: Internet
Author: User

As a developer (Web front-end JavaScript development), non-normative development not only makes future code maintenance difficult, but also does not benefit the team's cooperation, and often leads to code security and execution efficiency problems. I have worked with colleagues who have not developed in accordance with the norm in the development work, and cooperate with him can not use "happy" to describe. Now I write the purpose of this article in addition to share with you a little experience, more is the hope for the future partners can play a certain role in reference. Of course, if I say there are unscientific places also hope that the predecessors of a lot of advice. The following sub-entries list the various specifications, which are based on the problem of colleague coding, and other specifications agreed by some industries may not be mentioned. Tiantai Yi Zhuang Metallurgy

1. Make sure the code is compressed without errors

For large JavaScript projects, it is common to compress all JavaScript files contained in the project when the product is released, such as by using the Google Closure Compiler service to compress the code. The new jquery has used this tool to compress the code, which generally removes comments written at development time, removes all whitespace and line breaks, and even replaces the long variable name with a short, meaningless variable name, which is designed to speed up the download of files while also reducing the amount of additional data traffic that comes with Web access. In addition to code protection also played a little role, at least after the compression of the code even if it is not so easy to read. To be able to correct the code through compression, the general requirements of the statement to the normal end of the semicolon, curly braces must also be strictly completed, in particular, the requirements of the compression tool. So if you do not do it at the beginning, then it is a waste of time to go back and look for errors after a compression error.

2. Ensure that the code can pass the specific IDE's automatic formatting function

Generally more sophisticated development tools (such as Aptana Studio) have the code "auto-format" feature, which helps to achieve uniform line wrapping, indentation, space and other code layout, you can set your favorite formatting standards, such as the opening curly brace {whether another row. The purpose of this requirement is to make it easy for your development team members to take a copy of your code and read it in the IDE's automatic format for the style he likes or is familiar with. Your colleague needs to read your code, probably because you are writing a generic method that he will use in other module development, reading your code to get the most insight into the details of the method invocation and implementation, which is an effect that the simple API document cannot achieve.

3. Using standard document annotations

This requirement is the most basic, which is helpful to see the method at the method call specific instructions, you can also use the Companion document tool to generate HTML or other format development documents for other team members to read, you can try to use Jsdoc-toolkit. If your auto-generated API comes from an open platform, like the Facebook.com app, then your documents are for all developers in the world. It also makes it easier for team members to read your code, and with your parameter descriptions, team members can easily know how you write the method to participate in the implementation details. Of course, it is also convenient for future code maintenance, so even if the big project, after a long time, go back to pity Dorado things will not forget their own writing code is how the same thing.

4. Use a variable name that is meaningful to the specification

Using canonical variable names can improve the readability of your code, and as a major project developer, your own code is not only easy for others to read. Development of large projects, in fact, each person write code volume may be relatively large, standardized naming, and later to see their own code is clearly understandable, such as the future system upgrade or new features, modify the code to be more easily. If you find that the code you wrote at the beginning is not quite understood now, it is really a joke.

Of course, use a meaningful variable name as much as possible with the standard naming, like here: var me = This may not have var self = This is good, because self is a keyword in python, in Python Self is usually the use of language this. Look at the following example, plus S is obviously more scientific than no addition, so you can know that the variable name is a complex number, possibly an array, and so on:

View Source print?
1 varli = document.getElementsByTagName(‘li‘)
2 varlis = document.getElementsByTagName(‘li‘)
5. Do not use the raw deviation grammar

JavaScript as a dynamic scripting language, flexibility is both an advantage and a disadvantage, it is well known that different levels of dynamic language developers to achieve the same functionality written code in the specification or syntax there will be a big difference. In any case, the standard code less funny, not to complicate the simple problem, do not violate the principle of readability is what you should do.

For example, this statement: typeof (b) = = ' String ' && alert (b) should be changed to: if (typeof (b) = = ' string ') alert (b), like the previous usage, uses the && Operator Resolution mechanism: If the && pre-statement is detected to return false will no longer detect the next statement, in the code optimization also mentions the most likely to be the first to judge the situation, such as if the condition is less good, if the condition is more and the statement is long, the code readability is quite poor.

Another example: +function (a) {var p = A;} (' a ') should read: (function (a) {var p = A;}) (' a '), in fact, the + number in front of the function is the same as the () parentheses that contain function, which is the priority of operations, the latter is a common and easy to see the way to prevent variable pollution, such as a number of popular JavaScript framework is used in the following manner.

Another example of reducing code readability, such as: function Getpostiontxt (type) {return type = = 2? "Wild": (Type = = 3?) "Mall": (type = = 4?) "copy": null));} Should be changed to: function Getpostiontxt (type) {var typedata={"2": "Wild", "3": "Mall", "4": "Dungeon"};if (Typedata[type]) return typedata[ Type]; else return null;}. If the type is a continuous integer starting from 0, then it is simpler to use the array directly, and the result looks much clearer, seeing that the nested head of the multilayer ternary expression above is not faint.

6. Not in the statement non-assignment place born in Chinese

The statement should not appear in Chinese I think it is generally known that although this does not affect the operation of the program, but obviously there is back industry standard requirements, of course, we are not using "easy language" to do development. On this issue, I did not want to take it out to say, but I did meet someone to do, do not know whether it is because his English is too bad, at least can also use pinyin bar, in addition to seek translation tools to help also good choice. I would like to cite, for example, the following writing in the present teaching is also understandable:

this.user[' name '] = ' Zhang San ' or this.user. Name = ' Zhang San '

7. Define the parameters of the fixed number of functions clearly

A fixed number of parameters inside a function does not use arguments to get parameters, because this way, if you define a method that contains more than one script, you cannot see at a glance what parameters the method accepts, and the number of parameters. such as the following:

View Source print?
1 var$ = function(){return document.getElementById(arguments[0]);}应该改成:var $ = function(elemID){returndocument.getElementById(elemID);}
8. Do not be passionate about dynamic event binding

Although it is known that events can be dynamically bound, such as using AddEventListener or the Bind method using jquery, it is also known that using dynamic event binding can make XHTML cleaner, but in general I recommend that you write the event directly on the DOM node. I think this will make the code easier to maintain, because in doing so, we can easily see what element is bound to when we look at the source code, and simply say that it's easier to know what method script a button or link clicked Si cho.

9. Reduce the coupling between code and XHTML

Instead of relying too much on some of the DOM's content features to invoke different scripting code, you should define methods for different functions and then invoke them on the DOM, so that regardless of whether the DOM is a button or a link, the call to the method is the same, such as the following implementation obviously has a problem:

View Source print?
01 functionmyBtnClick(obj)
02 {
03  if(/确定/.test(obj.innerHTML))
04   alert(‘OK‘);
05  elseif(/取消/.test(obj.innerHTML))
06   alert(‘Cancel‘);
07  else
08   alert(‘Other‘);
09 }
10 <a herf="javascript:;"onclick="myBtnClick(this)">确定</a><a herf="javascript:;"onclick="myBtnClick(this)">取消</a>

The above example actually handles two things within a function, which should be divided into two functions, like the one above, if the link is changed to a button, such as: <input type= "button" onclick= "Mybtnclick (This)" value= "OK "/>, then the Mybtnclick function inside the obj.innerhtml is a problem, because this time should be obj.value, in addition, if the name of the button from Chinese to English will also be problematic, so this practice problem too much."

10. A function should return a uniform data type

Because Javascrip is a weak type, when writing a function some people seem to be more casual about the return type, and I think it should be returned as a strongly typed language, and look at the following two examples:

View Source print?
01 functiongetUserName(userID)
02 {
03  if(data[userID])
04   returndata[userID];
05  else
06   returnfalse;
07 }
08 应该改为:
09 functiongetUserName(userID)
10 {
11  if(data[userID])
12   returndata[userID];
13  else
14   return"";
15 }

If this method is defined in C #, we know that the data type it is prepared to return should be a string, so if we do not find this data we should return an empty string instead of returning a Boolean or other inappropriate type. This does not affect the future invocation of the function, because the returned empty string can be considered "non" in logical judgment, that is, the same as false, unless we use all equals "= = =" or typeof to judge.

11. Specification definition JSON object, complete double quotation mark

It's certainly good to use standards, so why do people not use standards? I think it may be lazy or habit problem. Maybe someone will tell me that writing less quotes can reduce the size of the file, which I think makes sense but not the point. For JSON data returned by the server, using the standard structure can be easily viewed with the Jsonview plugin of the Firefox browser (as in the case of XML), and if you are developing with jquery, the latest version of jquery1.4+ is a higher requirement for JSON format. , you can check the jquery update documentation yourself. For example: {name: "Tom"} or {' name ': ' Tom '} should be changed to {"Name": "Tom"}.

12. Do not leave the document in the future identify code snippets that are no longer used

When code is resized or refactored, previously written code that is no longer used should be deleted in a timely manner, and can be cut into a temporary file if it is thought to have some useful value. Stay in the project not only to increase the volume of the file, this to other members of the team even themselves have a certain interference, afraid to see their own code in the future do not understand what this method is doing, whether it has been used. Of course, you can use the document comment label @deprecated to identify this method as not recommended.

13. Do not repeat the methods that other team members have implemented

For large projects, some development members generally implement some common methods, while others are familiar with these common methods, and then call them directly when they need to write their own modules, rather than as some developers like to "go it alone" and not read these generic method documents at all. In their own code to write again the implementation, which not only produces unnecessary code volume, of course, it will affect team development efficiency, this is not a team spirit of performance, is the tragedy of repeating the wheel.

For example, in a generic class file Common.js has the function $ (elemid) {return document.getElementById (elemid)} Then there should be no repetition of this functional function in Mail.js, especially for some complex methods.

14. Call the appropriate method

When there are several ways to achieve similar functionality, we still have to choose the most appropriate method based on the scenario. The following is the jquery framework of the two Ajax methods to illustrate. If you determine that the data returned by the server is JSON, you should use $.getjson directly instead of using $.get to get the data and then use the Eval function to turn it into a JSON object. You should also take the practice of specifying the return data type (setting the datatype parameter) if the request is to transfer a large amount of data and not to use $.post. If we use $.getjson, we can see in the code that the request server is returning JSON.

Warm tip: After jQuery1.4, if the server has set the data output ContentType, such as ASP. Response.ContentType = "Application/json", then $.get will be with $. There is no difference in the use of Getjson.

15. Use the appropriate controls to store the right data

It was found that a div was used to save the JSON data for future use after the page was downloaded, like this: <div id= "JSON" >{"name": "Tom"}</DIV> obviously this div is not used for interface display, if you do The use of HTML files for data caching, at least change to the hidden domain to save the data more reasonable, such as: <input type= "hidden" value= "{" name ":" Tom "}"/>.

In fact, you can also use the Window object to save some data, like the above example, we can directly include such a script block on the AJAX request page: <script>window.userdata = {"Name": "Tom"};</script When you finish executing $ ("#MyDiv") in the AJAX request callback function. HTML (data), this variable is immediately available on window. If the first method is used, it will inevitably be eval (document.getElementById ("UserData"). InnerHTML). If you store a large amount of data in the Window object, it is necessary to manually clean up the data when it is not used, which will not disappear until the browser refreshes or restarts, which increases the memory overhead.

16. Never Ignore code optimization work

Code optimization is the goal that every programmer should strive to achieve, and it should be the constant pursuit of programmers. Write code, should not rush to implement the function, to think about how to write code, code execution efficiency is better.

For example: Suppose there is a quick way to define getElementById Functoin $ (elemid) {return document.getElementById (elemid)}, then someone might write a code like this $ ("mydiv") . Parentnode.removechild ($ ("mydiv")), actually performed here two times getElementById Dom lookup, if changed to this will be better: var mydiv = $ ("mydiv"); MyDiv.parentNode.removeChild (mydiv). Fortunately getElementById Dom lookup calculation is relatively fast, if replaced by getElementsByTagName should focus on optimization. The jquery development team also reminds you to be aware of this problem.

Of course, code optimization techniques also require personal accumulation. I had a friend who told me that he never had to think about optimization because they used the Xeon Quad-core server, which I think is ridiculous.

17. Analysis of the planning document, the object-oriented approach to interface definition and code organization

This ability is very important for every programmer, and this is an important factor in determining the level of a programmer. The ability to refine and abstract the needs of different classes, and then write code in a structured manner, so that the code structure is clear, readable, code is easy to maintain, not too procedural and disorganized, so it is a good programmer.

How to write a canonical JavaScript code

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.