Home > Web Front-end > JS Tutorial > How to write standardized JavaScript code

How to write standardized JavaScript code

黄舟
Release: 2016-12-20 15:37:48
Original
918 people have browsed it

As a developer (WEB front-end JavaScript development), non-standard development not only makes it difficult to maintain code in the future, but is also not conducive to team cooperation. It usually also brings problems with code security and execution efficiency. In my development work, I have worked with colleagues who did not develop according to the standards. Working with him cannot be described as "pleasant". Now, the purpose of writing this article is not only to share a little experience with you, but also to hope that it can serve as a reference for future partners. Of course, if what I say is unscientific, I hope that seniors from all walks of life can give me some advice. The various standard requirements are listed below in sub-items. These requirements are all proposed for colleagues' coding problems. Other standards agreed by many industries may not be mentioned again.

1. Ensure that there are no errors after code compression

For large JavaScript projects, all JavaScript files contained in the project will generally be compressed when the product is released. For example, you can use Google Closure Compiler Service to compress the code. The new version of jQuery has Use this tool to compress the code instead. This will generally remove the comments written during development, remove all spaces and newlines, and even replace the original long variable names with short and meaningless variable names. The purpose of this is It speeds up file downloads and reduces the extra data traffic caused by website access. It also plays a small role in code protection. At least the compressed code is not easy to read even if it is restored. In order for the code to be compressed correctly, it is generally required that the statement must end normally with a semicolon, and the braces must also end strictly, etc. The specific requirements also depend on the requirements of the compression tool. So if you don’t do it according to the standards at the beginning, it will be a waste of time to go back and find the errors after the compression goes wrong.

2. Ensure that the code can pass the automatic formatting function of a specific IDE

Generally, more complete development tools (such as Aptana Studio) have the function of "automatic formatting" of code. This function helps to achieve unified line breaks, indentation, and spaces. When the code is organized, you can set your favorite formatting standards, such as whether the left brace { should start a new line. The purpose of achieving this requirement is to facilitate your development team members to take a copy of your code and use the IDE to automatically format it into a style they like or are familiar with for reading. Your colleague needs to read your code, maybe because you write a common method, which he also needs to use in the development process of other modules. Reading your code can give you the deepest understanding of the details of method calling and implementation. This is a simple API document. effects that cannot be achieved.

3. Use standard documentation comments

This requirement is considered the most basic. This is helpful to see the specific parameter passing prompts of the method at the method call. You can also use the supporting documentation tool to generate development documents in html or other formats. For other team members to read, you can try using jsdoc-toolkit. If your automatically generated API comes from an open platform, like the facebook.com application, then your documentation is open to all developers in the world. In addition, writing complete comments will make it easier for team members to read your code. Through your parameter description, team members can easily know the implementation details of the method you wrote. Of course, it also facilitates code maintenance in the future, so that no matter how big the project is, if you go back and change something after a long time, you will not forget what the code you wrote at that time was.

4. Use standardized and meaningful variable names

Using standardized and meaningful variable names can improve the readability of the code. As a development member of a large project, the code you write is not only easy for others to understand. When developing large projects, in fact, everyone may write a relatively large amount of code. Standard naming will make it clear and easy to understand when you look back at your code in the future. For example, when the system is upgraded or new functions are added in the future, it will be much easier to modify the code. . It would be a big joke if you find in the end that the code you originally wrote cannot be understood now.

Of course, use meaningful variable names and try to use standard naming, such as here: var me = this may not be as good as var self = this, because self is a keyword in Python, and in Python self is the common language this usage. Look at the following example again. Adding s is obviously more scientific than not adding it. This way we can know that the variable name stores a plural number, maybe an array, etc.:

var li = document.getElementsByTagName('li')
var lis = document.getElementsByTagName('li')
Copy after login

5. Don’t use biased syntax

As a dynamic scripting language, JavaScript’s flexibility is both an advantage and a disadvantage. As we all know, developers of different levels of dynamic languages ​​have different standards or syntax for the codes written to implement the same function. Big difference. No matter what, what everyone should do is standardize coding and avoid making mistakes, not complicate simple problems, and not violate the principle of code readability.

For example, this statement: typeof(b) == 'string' && alert(b) should be changed to: if (typeof(b) == 'string') alert(b), like the previous usage, using && Operator parsing mechanism: If the statement before && is detected and returns false, the subsequent statement will no longer be detected. In terms of code optimization, it is also mentioned that the most likely situation will be judged first. This way of writing is better if there are fewer conditions, but if there are more conditions Moreover, the statements are also long, so the readability of the code is quite poor.

Another example: +function(a){var p = a;}('a') should be changed to: (function(a){var p = a;})('a'). In fact, the + in front of function The function of the () brackets is the same as that of the () brackets containing functions. They both play the role of operation priority. The latter is a common and easy-to-understand method to prevent variable pollution. For example, many popular JavaScript frameworks use the latter method.

Let’s talk about another example that reduces the readability of the code, 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":"Copy"};if (typeData[type] ) return typeData[type]; else return null;}. If type is an uninterrupted integer starting from 0, then it is simpler to use the array directly. The result looks much clearer. Are you not dizzy after seeing the previous multi-layered ternary expression nesting?

6. Do not write Chinese in non-assignment areas of statements

Chinese characters should not appear in statements. I think most people know that although this does not affect the running of the program, it obviously complies with industry standard requirements. Of course, we are not using "Easy Language" "Do development. Regarding this issue, I originally didn’t want to talk about it, but I did encounter someone who did this. I don’t know if it’s because his English is so bad. At least he can use Pinyin, and I’m looking for translation tools. Helping is also a good option. I give an example as follows. It is understandable if the following writing appears in teaching:

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

7. Clearly define function fixation Number of parameters

Functions with a fixed number of parameters do not use arguments to obtain parameters. Because of this, if the method you define contains a lot of scripts, you cannot see at a glance what parameters the method accepts and the number of parameters. . For example, like the following:

var $ = function(){return document.getElementById(arguments[0]);}应该改成:var $ = function(elemID){return document.getElementById(elemID);}
Copy after login

8. Don’t be crazy about dynamic event binding

Although I know that events can be dynamically bound, such as using addEventListener or using jQuery’s bind method, and I also know that using dynamic event binding can make XHTML cleaner, but generally In this case, I still recommend writing the event directly on the DOM node. I think this can make the code easier to maintain, because in this way, we can easily know which Element is bound to which method when viewing the source code. Simply put, this makes it easier to know what method script is called when a button or link is clicked.

9. Reduce the coupling between code and Links and method calls are all the same. For example, the following implementation will obviously have problems:

function myBtnClick(obj)
{
 if (/确定/.test(obj.innerHTML)) 
  alert('OK');
 else if (/取消/.test(obj.innerHTML)) 
  alert('Cancel');
 else
  alert('Other');
}
<a herf="javascript:;" onclick="myBtnClick(this)">确定</a><a herf="javascript:;" onclick="myBtnClick(this)">取消</a>
Copy after login

The above example actually handles two things in one function, and should be divided into two functions, like the above writing, if the link Change it to a button, for example, change it to this: , then there will be a problem with obj.innerHTML inside the myBtnClick function, because at this time It should be obj.value. In addition, there will be problems if the button name is changed from Chinese to English, so this approach has too many problems.

10. 一个函数应该返回统一的数据类型

因为JavaScrip是弱类型的,在编写函数的时候有些人对于返回类型的处理显得比较随便,我觉得应该像强类型语言那样返回,看看下面的两个例子:

function getUserName(userID)
{
 if (data[userID])
  return data[userID];
 else
  return false;
}
应该改为:
function getUserName(userID)
{
 if (data[userID])
  return data[userID];
 else
  return "";
}
Copy after login

这个方法如果在C#中定义,我们知道它准备返回的数据类型应该是字符串,所以如果没有找到这个数据我们就应该返回空的字符串,而不是返回布尔值或其它不合适的类型。这并没有影响到函数将来的调用,因为返回的空字符串在逻辑判断上可被认作"非",即与false一样,除非我们使用全等于"==="或typeof进行判断。

11. 规范定义JSON对象,补全双引号

使用标准肯定是有好处的,那么为什么还是有人不使用标准呢?我想这可能是懒或习惯问题。也许还会有人跟我说,少写引号可以减轻文件体积,我认为这有道理但不是重点。对于服务器返回的JSON数据,使用标准结构可以利用Firefox浏览器的JSONView插件方便查看(像查看XML那样树形显示),另外你如果使用jQuery做开发,最新版本jQuery1.4+是对JSON格式有更高要求的,具体的可以自己查阅jQuery更新文档。比如:{name:"Tom"}或{'name':'Tom'}都应该改成{"name":"Tom"}。

12. 不在文件中留下未来确定不再使用的代码片段

当代码调整或重构后,之前编写的不再使用的代码应该及时删除,如果认为这些代码还有一定利用价值可以把它们剪切到临时文件中。留在项目中不仅增加了文件体积,这对团队其它成员甚至自己都起到一定干扰作用,怕将来自己看回代码都搞不懂这方法是干什么的,是否有使用过。当然可以用文档注释标签@deprecated把这个方法标识为不推荐的。

13. 不重复定义其他团队成员已经实现的方法

对于大型项目,一般会有部分开发成员实现一些通用方法,而另外一些开发成员则要去熟悉这些通用方法,然后在自己编写模块遇到有调用的需要就直接调用,而不是像有些开发者喜欢"单干",根本不会阅读这些通用方法文档,在自己代码中又写了一遍实现,这不仅产生多余的代码量,当然也是会影响团队开发效率的,这是没有团队合作精神的表现,是重复造轮子的悲剧。

比如在通用类文件Common.js有定义function $(elemID){return document.getElementById(elemID)}那么就不应该在Mail.js中再次出现这一功能函数的重复定义,对于一些复杂的方法更应该如此。

14. 调用合适的方法

当有几个方法都可以实现同类功能的时候,我们还是要根据场景选择使用最合适的方法。下面拿jQuery框架的两个AJAX方法来说明。如果确定服务器返回的数据是JSON应该直接使用$.getJSON,而不是使用$.get得到数据再用eval函数转成JSON对象。如果因为本次请求要传输大量的数据而不得以使用$.post也应该采用指定返回数据类型(设置dataType参数)的做法。如果使用$.getJSON,在代码中我们一眼能看出本次请求服务器返回的是JSON。

温馨提示:jQuery1.4后,如果服务器有设置数据输出的ContentType,比如ASP.NET C#设置 Response.ContentType = "application/json",那么$.get将与$.getJSON的使用没有什么区别。

15. 使用合适的控件存储合适的数据

I once found someone using DIV to save JSON data for future use after the page is downloaded, like this:

{ "name":"Tom"}
, obviously this DIV It is not used for interface display. If you must do this to achieve the effect of using HTML files for data caching, it is more reasonable to at least use a hidden field to store this data. For example, change it to: .

In fact, you can also use the window object to save some data. Like the example above, we can directly include such a script block in the AJAX request page:

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template