Write your JavaScript.

Source: Internet
Author: User

About
    • Public number: Front hula hoop (love-fed)
    • My blog: Laub's Blog
    • Column: Front hula hoop
Objective

In the actual work, we should often see some functional problems, but the coding style and code is very bad, which often makes people dare not read down, and even affect the mood of the reader day. Not only are they hard to read, they are difficult to maintain, they are usually from novice programmers who are just getting started, and they come from the old programmer who has worked for years. So the purpose of this article is to help JavaScript learners who have not developed a good coding style and lack the appropriate coding awareness to improve their coding image.

Coding image

Above I put forward the concept of coding image, I personally think:

编码形象 = 编码风格 + 编码规范

A good coding image is equal to a well-dressed youth, which is the most straightforward and straightforward way for programmers to understand your ability to excel.

Let's look at a bad coding image:

//打个招呼function func(){    var age=18,sex=‘man‘;    var greeting=‘hello‘;    if(age<=18&&sex==‘man‘){        console.log(greeting+‘little boy‘)    }    ...}func()

The above code is all shrunk together, lacks the standard consciousness, the reading experience is very poor, cannot bear to look straight.

Then look at a good code image:

// 打个招呼function greetFn() {    var age = 18,        sex = ‘man‘,        greeting = ‘hello‘;    if (age <= 18 && sex === ‘man‘) {        console.log(greeting + ‘little boy‘);    }    ...};greetFn();

Does the code above feel much more comfortable?

Thus it is important to develop a good coding image, and this article mainly explains the coding image based on JavaScript, that is, the coding style and coding specification based on JavaScript.

So what is the coding style, what is the coding specification, and what is the difference between the two?

Coding style

First of all, since the coding style is style, there is no right or wrong. Just like everyone's dress is different, some people wear more appropriate, some people wear more casual.

And in JavaScript coding style, there is a more appropriate style, especially in team development, we can not casually write their own style.

Here are a few random coding styles, and compare them with a good coding style.

1. Reasonable comment
// 不推荐的写法var name = ‘劳卜‘;//代码和注释之间没有间隔if (name) {    /*     *注释之前无空行     *星号后面无空格     */}
// 推荐的写法var name = ‘劳卜‘; // 代码和注释之间有间隔if (name) {    /*     * 注释之前有空行     * 星号后面有空格     */}
2. Reasonable intervals
// 不推荐的写法var name=‘劳卜‘; // 等号和两侧之间没有间隔// if块级语句间没有间隔if(name){    console.log(‘hello‘);}
// 推荐的写法var name = ‘劳卜‘; // 等号和两侧之间有间隔// if块级语句间有间隔if (name) {    console.log(‘hello‘);}
3. Proper indentation
// 不推荐的写法:没有合理缩进function getName() {console.log(‘劳卜‘); }
// 推荐的写法:合理缩进function getName() {    console.log(‘劳卜‘);}
4. Reasonable blank line
// 不推荐的写法: 代码功能块之间没有空行function getName() {    var name = ‘劳卜‘;    if (name) {        console.log(‘hello‘);    }}
// 推荐的写法:代码功能块之间有空行function getName() {    var name = ‘劳卜‘;    if (name) {        console.log(‘hello‘);    }}
5. Proper naming
// 不推荐的写法var getName = ‘劳卜‘; // 变量命名前缀为动词// 函数命名前缀为名词function name() {   console.log(‘hello‘);}
// 推荐的写法var name = ‘劳卜‘; // 变量命名前缀为名词// 函数命名前缀为动词function getName() {   console.log(‘hello‘);}
6. Reasonable declaration
// 不推荐的写法:函数在声明之前使用getName(); function getName() {    console.log(‘hello‘);}
// 推荐的写法:函数在声明之后使用function getName() {    console.log(‘hello‘);}getName();
7. Reasonable End
// 不推荐的写法:没有使用分号结尾var name = ‘劳卜‘ var getName = function() {    console.log(‘hello‘)}
// 推荐的写法:使用分号结尾var name = ‘劳卜‘; var getName = function() {    console.log(‘hello‘);};

The above main list of 7 more common coding style examples are compared, in the recommended wording and not recommended in the wording of the two are not right and wrong, but the recommended wording is easier to read and maintenance, more suitable for team development, but also a good image of the embodiment of the code.

Coding specifications

For the code specification, since it is the norm, then we should follow certain rules to write. Arbitrarily writing code that violates the coding specifications can lead to program errors and potential bugs, so it should be more rigorous relative to the coding style, and someone will include the coding style in the coding specification.

Here are a few examples of common example code:

1. Compare parameters
// 不推荐的写法:==和!=比较时会进行类型转换,应尽量避免使用var num = 123;if (num == ‘123‘) {    console.log(num);} else if (num != ‘321‘) {    console.log(‘321‘);}
// 推荐的写法:使用===和!==来进行比较var num = 123;if (num === ‘123‘) {    console.log(num);} else if (num !== ‘321‘) {    console.log(‘321‘);}
2. Package if statement
// 不推荐的写法:if语句不用大话号包裹会出现潜在bugvar num = 123;if (num === ‘123‘)    console.log(num);
// 推荐的写法:if语句用大话号包裹var num = 123;if (num === ‘123‘) {    console.log(num);}
3. Use eval carefully
// 不推荐的写法:应避免使用eval,不安全,非常耗性能(一次解析成js语句,一次执行)var json = ‘{"name": "劳卜", "func": alert("hello")}‘;eval(‘(‘ + json + ‘)‘); // 弹出“hello”
// 推荐的写法var json = ‘{"name": "劳卜", "func": alert("hello")}‘;JSON.parse(json); // 校验报错
4. Type of judgment
// 不推荐的写法:用typeof来判断构造函数创建的对象var str = new String(‘劳卜‘); console.log(typeof str); // ‘object‘
// 推荐的写法:用instanceof来判断构造函数创建的对象var str = new String(‘劳卜‘); console.log(str instanceof String); // true
5. Detection Properties
// 不推荐的写法:使用undefined和null来检测一个属性是否存在if (obj[‘name‘] !== undefined) {    console.log(‘name属性存在‘); // 若obj.name为undefined时则会导致判断出错}if (obj[‘name‘] !== null) {    console.log(‘name属性存在‘); // 若obj.name为null时则会导致判断出错}
// 推荐的写法:使用in运算符来检测对象属性是否存在,使用hasOwnProperty方法来检测不包含原型链上的对象属性是否存在if (‘name‘ in obj) {    console.log(‘name属性存在‘);}if (obj.hasOwnProperty(‘name‘)) {    console.log(‘name属性存在‘);}

The above is a list of 5 common coding specifications examples, reasonable to standardize their own code can greatly reduce unnecessary maintenance costs and potential bug risk, for JavaScript learners should be remembered in mind.

Conclusion

"The program is for people to read, but occasionally let the computer do it." "We cannot personally destroy our own code image for the sake of momentary convenience, which can cause unnecessary trouble to others and the whole project."

This article refers to the book, "Writing maintainable JavaScript."

?

Write your JavaScript.

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.