Home > Web Front-end > JS Tutorial > body text

Master JavaScript tips to help you improve code quality

coldplay.xixi
Release: 2020-12-24 17:28:13
forward
2067 people have browsed it

javascriptThe column introduces tips to improve the quality of article code

Master JavaScript tips to help you improve code quality

Recommended (free) :javascript(Video)

Introduction

Mainly introduces the following points:

  • Refining function

  • Merge duplicate conditional fragments

  • Refining conditional branch statements into functions

  • Use loops appropriately

  • Let the function exit early instead of nested conditional branches

  • Pass object parameters instead of too long parameter lists

  • Use less ternary operators

  • Use chain calls rationally

  • Decompose large classes

This article will be continuously updated, please feel free to add any deficiencies in the comment area.

1. Refining functions

Benefits:

  • Avoid overly large functions.

  • Independent functions help code reuse.

  • Independent functions are easier to overwrite.

  • If the independent function has a good name, it itself plays the role of a comment.

  • Semantic implementation of multiple separate sections of logic in different functions can make the code logic clear and clearly see what each step is doing.

Code example:

Realize obtaining data, then operate dom to display data, and finally add events

Before function refining

// 逻辑都写在一起,需要将所有逻辑看完才知道这段代码是干嘛的,局部逻辑无法复用
function main() {
    $.ajax.get('/getData').then((res) => {
        const ul = document.getElementById('ul');
        ul.innerHTML = res.list.map(text => `<li class="li">${text}</li>`).join(&#39;\n&#39;);
        const list = document.getElementsByClassName(&#39;li&#39;);
        for (let i = 0; i < list.length; i ++) {
            list[i].addEventListener(&#39;focus&#39;, () => {
                // do something
            });
        }
    });
}
Copy after login

After function refining

function getData() {
    return $.ajax.get(&#39;/getData&#39;).then((res) => res.data.list);
}
function showList(list) {
    const ul = document.getElementById(&#39;ul&#39;);
    ul.innerHTML = list.map(text => `<li class="li">${text}</li>`).join(&#39;\n&#39;);
}
function addEvent() {
    const list = document.getElementsByClassName(&#39;li&#39;);
    for (let i = 0; i < list.length; i ++) {
        list[i].addEventListener(&#39;focus&#39;, () => {
            // do something
        });
    }
}
// 逻辑清晰,一眼读懂每一步在做什么,某些提炼出来的函数还可以被复用
async function main() {
    const list = await getData(); // 获取数据
    showList(list); // 显示页面
    addEvent(); // 添加事件
}
Copy after login

2. Merge duplicate conditional fragments

If there are some conditional branch statements in a function body, and there are some repeated conditional statements scattered inside these conditional branch statements code, then it is necessary to merge and remove duplicates.

// 合并前
function main( currPage ){
    if ( currPage <= 0 ){
        currPage = 0;
        jump( currPage ); // 跳转
    }else if ( currPage >= totalPage ){
        currPage = totalPage;
        jump( currPage ); // 跳转
    }else{
        jump( currPage ); // 跳转
    }
};
// 合并后
function main( currPage ){
    if ( currPage <= 0 ){
        currPage = 0;
    }else if ( currPage >= totalPage ){
        currPage = totalPage;
    }
    jump( currPage ); // 把jump 函数独立出来
};
Copy after login

3. Refining conditional branch statements into functions

Complex conditional branch statements are an important reason why the program is difficult to read and understand, and can easily lead to a huge function. Sometimes conditional branch statements can be refined into semantic functions to make the code more intuitive and logically clear.

// 根据不同季节决定打折力度
function getPrice( price ){
    var date = new Date();
    if ( date.getMonth() >= 6 && date.getMonth() <= 9 ){ // 夏天
        return price * 0.8;
    }
    return price;
};
// 是否是夏天
function isSummer(){
    var date = new Date();
    return date.getMonth() >= 6 && date.getMonth() <= 9;
};
// 提炼条件后
function getPrice( price ){
    if ( isSummer() ){
        return price * 0.8;
    }
    return price;
};
Copy after login

4. Reasonable use of loops

If multiple pieces of code are actually responsible for some repetitive work, they can be replaced by loops to reduce the amount of code.

// 判断是什么浏览器
function getBrowser(){
    const str = navigator.userAgent;
    if (str.includes(&#39;QQBrowser&#39;)) {
return &#39;qq&#39;;
    } else if (str.includes(&#39;Chrome&#39;)) {
return &#39;chrome&#39;;
    } else if (str.includes(&#39;Safari&#39;)) {
        return &#39;safri&#39;;
    } else if (str.includes(&#39;Firefox&#39;)) {
        return &#39;firefox&#39;;
    } else if(explorer.indexOf(&#39;Opera&#39;) >= 0){
        return &#39;opera&#39;;
    } else if (str.includes(&#39;msie&#39;)) {
        return &#39;ie&#39;;
    } else {
        return &#39;other&#39;;
    }
};
// 循环判断,将对应关系抽象为配置,更加清晰明确
function getBrowser(){
    const str = navigator.userAgent;
    const list = [
        {key: &#39;QQBrowser&#39;, browser: &#39;qq&#39;},
        {key: &#39;Chrome&#39;, browser: &#39;chrome&#39;},
        {key: &#39;Safari&#39;, browser: &#39;safari&#39;},
        {key: &#39;Firefox&#39;, browser: &#39;firefox&#39;},
        {key: &#39;Opera&#39;, browser: &#39;opera&#39;},
        {key: &#39;msie&#39;, browser: &#39;ie&#39;},
    ];
    for (let i = 0; i < list.length; i++) {
        const item = list[i];
        if (str.includes(item.key)) {return item.browser};
    }
    return &#39;other&#39;;
}
Copy after login

5. Let the function exit early instead of nested conditional branches

Let the function return early with multiple exits and replace nested conditional branches.

function del( obj ){
    var ret;
    if ( !obj.isReadOnly ){ // 不为只读的才能被删除
        if ( obj.isFolder ){ // 如果是文件夹
            ret = deleteFolder( obj );
        }else if ( obj.isFile ){ // 如果是文件
            ret = deleteFile( obj );
        }
    }
    return ret;
};
function del( obj ){
    if ( obj.isReadOnly ){ // 反转if 表达式
        return;
    }
    if ( obj.isFolder ){
        return deleteFolder( obj );
    }
    if ( obj.isFile ){
        return deleteFile( obj );
    }
};
Copy after login

6. Pass object parameters instead of too long parameter lists

If the function parameters are too long, the risk of errors increases. It is important to ensure that the order of passing is correct. The trouble is that the readability of the code will also become worse. Try to ensure that the parameters of the function are not too long. If multiple parameters must be passed, it is recommended to use objects instead.

Generally speaking, it is best not to have more than 3 function parameters

function setUserInfo( id, name, address, sex, mobile, qq ){
    console.log( &#39;id= &#39; + id );
    console.log( &#39;name= &#39; +name );
    console.log( &#39;address= &#39; + address );
    console.log( &#39;sex= &#39; + sex );
    console.log( &#39;mobile= &#39; + mobile );
    console.log( &#39;qq= &#39; + qq );
};
setUserInfo( 1314, &#39;sven&#39;, &#39;shenzhen&#39;, &#39;male&#39;, &#39;137********&#39;, 377876679 );
function setUserInfo( obj ){
    console.log( &#39;id= &#39; + obj.id );
    console.log( &#39;name= &#39; + obj.name );
    console.log( &#39;address= &#39; + obj.address );
    console.log( &#39;sex= &#39; + obj.sex );
    console.log( &#39;mobile= &#39; + obj.mobile );
    console.log( &#39;qq= &#39; + obj.qq );
};
setUserInfo({
    id: 1314,
    name: &#39;sven&#39;,
    address: &#39;shenzhen&#39;,
    sex: &#39;male&#39;,
    mobile: &#39;137********&#39;,
    qq: 377876679
});
Copy after login

7. Use less ternary operators

Ternary operator performance High, less code.

But the ternary operator should not be abused. We should use it in simple logic branches and avoid using it in complex logic branches.

// 简单逻辑可以使用三目运算符
var global = typeof window !== "undefined" ? window : this;
// 复杂逻辑不适合使用
var ok = isString ? (isTooLang ? 2 : (isTooShort ? 1 : 0)) : -1;
Copy after login

8. Reasonable use of chain calls

Advantages:

Chain calls are simple to use and require less code.

Disadvantages:

The disadvantage of chain calls is that it is inconvenient to debug. If we know that there is an error in a chain, we must first disassemble the chain before adding some Debug the log or add breakpoints to locate where the error occurs.

If the structure of the chain is relatively stable and not easy to be modified later, the chain type can be used.

var User = {
    id: null,
    name: null,
    setId: function( id ){
        this.id = id;
        return this;
    },
    setName: function( name ){
        this.name = name;
        return this;
    }
};
User
  .setId( 1314 )
  .setName( &#39;sven&#39; );
var user = new User();
user.setId( 1314 );
user.setName( &#39;sven&#39; );
Copy after login

9. Decomposing large classes

The decomposition of large classes is very similar to the refining of functions. If a class is too large, the logic will be unclear and difficult to understand and maintain.

Reasonable decomposition of major categories can make the logic of the class clear, and sub-modules can be easily reused.

10. Use bitwise operators

The performance of programming languages ​​for calculating multiplication and division is not high, but in some cases, using bitwise operators can improve the performance of operations such as multiplication and division.

// 按位右移
var n = parseInt(3 / 2); // 原始
var n = 3 >> 1; // 按位右移
Copy after login

The above is the detailed content of Master JavaScript tips to help you improve code quality. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template