How to make your JS code written more beautiful

This article summarizes the feeling of specification writing js good, used collection. Transfer: https://mp.weixin.qq.com/s/AtR94IL9BW9EXOTnKOilmA

1. Press the strongly typed style of writing code

JS is weakly typed, but write the code can not be too casual, too casual writing also reflects the bad coding style. Points described below:

(1) define the variables of time to specify the type, tells JS interpreter This variable is what type of data, rather than let the interpreter to guess, such as poor wording:
var num,
    str,
    obj;

It declares three variables, but in fact no use, because the interpreter does not know what type they are, good writing should be like this:

var num =0,
    str ='',
    obj =null;

Define a variable time gave him a default value, which not only facilitates the interpreter, but also convenient to read the code, he'll know the answer - these variables may know as what.

(2) do not change arbitrarily variable type, for example the following codes:
var num =5;
num ="-"+ num;

Line 1 which is an integer, the second row it into a string. Because JS will eventually be translated into assembler language, assembly language variable type is certainly to be determined, you put a integer into a string, then the interpreter would have to do some additional processing. And this coding style is discouraged, there is a variable is an integer line 1, line 10 into a string, line 20 and into a object, so let the people reading the code more confused above obviously is an integer, how suddenly turned into a string of. Good wording should be re-define a string variable:

var num =5;
var sign ="-"+ num;
(3) should return type of the function to be determined, for example, the following wording uncertain:
function getPrice(count){
    if(count <0)return"";
    elsereturn count *100;
}

getPrice This function may return an integer, may also return an empty string. Such writing is not very good, although it is in line with JS syntax, but this coding style is not good. You use this function people a bit confused, not directly add or subtract, multiply and divide, because if the return string operation, then the value is NaN. Function returns the type should be determined, as it will return Integer:

function getPrice(count){
    if(count <0)return-1;
    elsereturn count *100;
}

Then tell the user, or -1 if it means not legal. If the type is determined, interpreters do not have to do some extra work, you can run faster.

2. Reduce the Scope Lookup

(1) Do not let the code is exposed to the global scope

For example, the code run in the global scope:

    var map = document.querySelector("#my-map");
    map.style.height ="600px";
</script>

Sometimes you need to write directly to the page in a script, a script should pay attention to the label inside the context of the code are global scope, due to the global scope is more complex, look slower. Variables such as the above map, when the second lines in use, you need to look at this variable in the global scope, assumptions map is used inside a loop, it may be efficient in question. So we should make it a mess local scope:

<script>
!function(){
    var map = document.querySelector("#my-map");
    map.style.height ="600px";
}()
</script>

Top with a function for producing a local scope, it can also be used for ES6 block-level scope. Because this variable map directly hit in the current local scope, so do not go down on a scope (here is the global scope) searched, and find local scope is very fast. At the same time define variables directly in the global scope, it will pollute the window object.

(2) Do not abuse closures

The role of the closure is to allow the child to use the variable scope of its parent-level scope, while these variables in different closures are not visible. This led to the search for a variable time, if the current scope can not be found, you have to find the scope of its parent, up until you find a level ground, or to the global scope have not found . So if the closure nested deeper, so the longer it takes to find the variable. as follows:

function getResult(count){
    count++;
    function process(){
        var factor =2;
        return count * factor -5;
    }
    return process();
}

The above function code defines a process, in which the function search time count variable is higher than the local variable factor. In fact, this is not suitable for use closure, can be passed directly to the count process:

function getResult(count){
    count++;
    function process(count){
        var factor =2;
        return count * factor -5;
    }
    return process(count);
}

Find this count and time factor, it is a direct hit in the current scope. This tells us that if it is a global variable is used frequently when needed, you can use a local variable cache it, as follows:

var url ="";
if(window.location.protocal ==="https:"){
    url ="wss://xxx.com"+ window.location.pathname + window.location.search;
}

Frequent use of the window.location object, so you can put it cache about:

var url ="";
var location = window.location;
if(location.protocal ==="https:"){
    url ="wss://xxx.com"+ location.pathname + location.search;
}

Became engaged to a bureau becomes variable, so it will look significantly faster than the overall look, the code can also write a little less.

3. Avoid the use of ==

Here you may be in doubt, some people like to use == === Some people like to use, everyone's style is different, why do you want to force others to do with ===? == accustomed to people, not only because == === less than a knock on the keyboard. Why not promote the use of == it?

(1) If you have determined the type of a variable, then there is no need to use ==, and are as follows:
if(typeof num !="undefined"){

}
var num = parseInt(value);
if(num ==10){

}

The above are two examples of determining the type is a string, an integer. No need to use ==, and === directly on it.

(2) If the type of uncertainty, you should do it manually type conversions, rather than letting someone else or later you guess there are a type conversion, as follows:
var totalPage ="5";
if(parseInt(totalPage)===1){

}
(3) == use in JSLint check the time is not passed:
if(a == b){

}

JSLint following output:

Expected ‘===’ and instead saw ‘==’.
(4) == use and there may be some strange phenomenon, these strange phenomena may give the code embedded risks:
null==undefined          //true
'' == '0'                  //false
0  == ''                   //true
0  == '0'                  //true
'
 ' == 0            //true
new String("abc") == "abc" //true
new Boolean(true) == true  //true
true == 1                  //true

The above comparison is false with === when this is reasonable. For example, the first point turned out to be equal to null undefined, it is particularly surprising, since the two are null and undefined values unrelated to, null should be used as initialization null, while undefined is used to test whether a variable is not defined.
This is the first point of introduction strongly typed idea is the same.

4. Merge expression

If you use a code to achieve the 5 function code, it is often a code efficiency will be higher, and probably better readability

(1) substituted ternary operator with simple if-else

As above getPrice function:

function getPrice(count){
    if(count <0)return-1;
    elsereturn count *100;
}

Can be changed to:

function getPrice(count){
    return count <0?return-1: count *100;
}

This looks much cleaner than writing a if-else up. Of course, if you write if-else, compression tools will help you change it to form ternary operator:
function the getPrice (E) {return0> E -1:? E * 100}

(2) even the like

Even using other assignment expression returns the assigned value, and the execution order is from right to left, as follows:

overtime = favhouse = listingDetail ={...}

Sometimes you see someone write:

var age =0;
if((age =+form.age.value)>=18){
    console.log("你是成年人");
}else{
    consoe.log("小朋友,你还有"+(18- age)+"就成年了");
}

Also use the assignment expression returns a value, while if the assignment inside with its return value to make a judgment, then else there would have been worth it. + The above turned into an integer number of the character string.

(3) increment

It can be simplified by using the code increment. Below, each message sent, localMsgId incremented to 1:
chatService.sendMessage(localMsgId++, msgContent);

The reduced number of magic

For example, in the first 800 lines of a file, it came out the sentence:

dialogHandler.showQuestionNaire("seller","sell",5,true);

It will make people very confused, what the above four constants representing it, if I do not check the function of a variable declaration will not be able to quickly sense what is the use of these constants, respectively. These constants undetermined significance called "magic number."
It's better to give these constants a name, especially in some of the more critical. For example, the above code can be changed:

  var naireType ="seller",
    dialogType ="sell",
    questionsCount =5,
    reloadWindow =true;

naireHandler.showNaire(naireType, dialogType, questionsCount, reloadWindow);

This meaning is quite clear.

6. Use simplify code ES6

ES6 have been developed for many years, compatibility is also very good. Proper use, can make the code more simple and elegant.

(1) Use the arrow substituents small function function

There are many scenes using small functions, if you write a function, at least have to write three lines of code, but a line with an arrow function to get, for example, by an array descending order:

var nums =[4,8,1,9,0];
nums.sort(function(a, b){
    return b - a;
});

// output [9, 8, 4, 1, 0]
if the function with the arrow, as long as the line to get the sort:

var nums =[4,8,1,9,0];
nums.sort(a, b => b - a);

The code looks a lot cleaner, which will always be there as long as the setTimeout execute one line of code just fine, write a function always felt a little trouble with the way the string of not very good, so this is also the case with the arrow function Convenience:

setTimeout(()=> console.log("hi"),3000)

Arrow function called in C ++ / Java, and other languages inside Lambda expressions, Ruby relatively long has this grammatical form, and later C ++ / Java also implements this syntax.
Of course arrow function or Lambda expression applies not only to this line, multiple lines of code can be, but in a row when it was more obvious advantages.

(2) using the class ES6

Although the prototype class nature and use function of the ES6 is the same, all with prototype. But with the class can reduce the amount of code, while allowing the code to look the more tall, use the function to write so:

functionPerson(name, age){
    this.name = name;
    this.age = age;
}

Person.prototype.addAge =function(){
    this.age++;
};

Person.prototype.setName =function(name){
    this.name = name;
};

Use class code is added to the watch easy to read:

classPerson{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    addAge(){
        this.age++;
    }
    setName(name){
        this.name = name;
    }
}

And class can easily implement inheritance, static member functions, you do not need to go through a number of techniques to achieve the.

(3) string concatenation

以前要用+号拼接:
var tpl = '<div>'+ ' <span>1</span>'+ '</div>';
现在只要用两个反引号“”就可以了: ```var tpl = <div> <span>1</span> </div> ``` 另外反引号还支持占位替换,原本你需要: ```var page =5, type = encodeURIComponet("#js"); var url ="/list?page="+ page +"&type="+ type; ``` 现在只需要: ```var url =/list?page=\({page}&type=\){type}`;
就不用使用+号把字符串拆散了。 #####(4)块级作用域变量 块级作用域变量也是ES6的一个特色,下面的代码是一个任务队列的模型抽象:var tasks =[];
for(var i =0; i <4; i++){
tasks.push(function(){
console.log("i is "+ i);
});
}
for(var j =0; j < tasks.length; j++){
tasksj;
}
但是上面代码的执行输出是4,4,4,4,并且不是想要输出:0,1,2,3,所以每个task就不能取到它的index了,这是因为闭包都是用的同一个i变量,i已经变成4了,所以执行闭包的时候就都是4了。那怎么办呢?可以这样解决:var tasks =[];
for(var i =0; i <4; i++){
!function(k){
tasks.push(function(){
console.log("i is "+ k);
});
}(i);
}
for(var j =0; j < tasks.length; j++){
tasksj;
}
把i赋值给了k,由于k它是一个function的一个参数,每次执行函数的时候,肯定会实例化新的k,所以每次的k都是不同的变量,这样就输出就正常了。 但是代码看起来有点别扭,如果用ES6,只要把var改成let就可以了:var tasks =[];
for(let i =0; i <=4; i++){
tasks.push(function(){
the console.log ( "IS I" + I);
});
}
for (var J = 0; J <tasks.length; J ++) {
Tasks J ;
}
`` `
only three characters altered to achieve the purpose. Because there are a for loop braces, braces is an independent scope, let's define the scope of the independent variables in which its value is independent. Of course, even if I did not write braces for loop execution it is independent.
In addition to the above points, ES6 there are other more useful features, such as the Object assign, Promise, etc., can also help to create concise and efficient code.
Listed above myself in the actual writing some of the problems encountered in the process of code and some personal aspects that are important, there are other variable naming, indentation, comments, etc., it is not mentioned here. The style of writing code also reflects the quality of programming, some code looks very neat, and some people's code looks so painful. Enhance the quality of such programming need to consciously make some improvements, some people though the code is poorly, but he does not feel any problems. This requires more to learn someone else's code, or even learn about writing in other languages, a comparison of the two will be able to find differences, or look for this book, and what code complete such like.

Guess you like

Origin www.cnblogs.com/newcapecjmc/p/11833457.html