How to make your JS code more semantic

Source: Internet
Author: User

A, the JavaScript code that is not easy to understand

1. Judging

// Data type judgment if (Object.prototype.toString.call (str) = = = "[Object String]"    ) {//  dosomething (); };//  file type determine if(/.*\.css (? =\?| $)/.test ("/path/to/main.css")) {    //  dosomething ();}

2. Clear a queue

var Queue = ["Test1", "Test2", "test3"]; // Common Ways Queue.length =0=[];

3. Register a variable

// Register var repos == {   name: "A",   = {   name: "B",   content: {}};

The above few examples can not understand, the program is particularly simple, in the first example, we use the ToString method on the Object prototype chain to determine whether a variable is a string type, and using the regular to determine if a file is a CSS file. The code is easier to write, but what if we also need to determine if multiple objects are one of several types? For example, if we need to extract require dependencies in a string of code, should we think about how to organize our own code?

In the second example, setting the length of the array to 0, or resetting the variable with an empty array, is a very common way, but the current scenario is to empty a queue, can we use a more semantic form to render? For example, do we just need to empty the top five and the last three item of the queue?

In the third example, the registration of variables, put a bunch of registrations together, the above form is indeed a glance, if a B c D and so are separated interspersed between the hundreds of lines of code? Suddenly a repos["x" is a bit less intuitive.

To illustrate the ideas advocated in this article, some of the above explanations are vague and farfetched, please look down.

B, he's high code semantics

For the above three cases, the code is presented in a more semantic way:

1. Semantic variables

// Type judgment function Istype (type) {    returnfunction(o) {        return Object.prototype.toString.call (o) = = = ' [object ' + Type + '] ';    }} var isstring = istype ("String"); var isobject = Istype ("Object"); var isarray = Istype ("Array"); Isstring ("I ' m Barret Lee.") ); IsArray ([+]); IsObject ({}) ;

I don't think that much explanation is needed, the contrast

if (Object.prototype.toString.call (str) = = = "[Object String]"    ) {//  codehere ...}

It looks fresher and more.

// Extracting Constants var iscss =/.*\.css (? =\?| $)/; Iscss.test ("/path/to/main.css");

No matter how long iscss this regular code, when we see iscss this word can be as the name implies. Many people write the regular will not be extracted alone using a meaningful variable to store, add comments Fortunately, if not annotated, follow-up developers can only bite the bullet to understand the meaning of the code.

This kind of processing, in fact, increases the amount of code, but from an engineering perspective, it helps to improve the efficiency of development and the organization of the Code.

2. Semantic behavior

var Queue = ["Test1", "Test2", "test3"]; Queue.splice (0, queue.length);

The above code is highly semantic, starting with an index of 0, until the end of the queue, deleting all of the item in the queues. The extensibility of this writing is also better:

Queue.splice (2,4); // Delete 4 elements from index 2,

This is only a small example, some of the behavior requires a lot of code combination processing, if there is no good combination of the same behavior of code, the entire structure is very lax, not conducive to reading.

// Register var repos=[]; function Register () {     = o;} Register ({    name:"A",    content;{}});

Compare US before

Repos["a"] ={    name:"A",    content;{}     };

Does the degree of semantics improve?

C, summary

The optimization of the code requires a lot of dimensions to consider. But the optimization of the code is not to reduce the amount of code, sometimes we need to add code to improve the readability of the code.

    • Tag variables correctly
    • Encapsulate an action
    • Note the notation of the function
    • Something that is not easy to understand, plus a comment

In this paper, I hope that you can trigger the sensitivity of the code optimization of the thinking, write a person's thumb code ~

How to make your JS code more semantic

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.