Home > Web Front-end > JS Tutorial > How to make JavaScript code more semantic

How to make JavaScript code more semantic

黄舟
Release: 2017-03-17 14:46:29
Original
1024 people have browsed it

Semantic This word is used more often in HTML, that is, selecting appropriate tags based on the structure of the content. Its role should not be underestimated:

  • gives tags meaning and makes the code structure clearer. Although we can add class to the tag to identify it, this form of expressing the ontology through attributes will It seems not direct enough, and also redundant to a certain extent.

  • Optimize search engines (SEO). Well-structured web pages have a high affinity for search engines. Baidu and Google have also given many suggestions (standards) for structuring web pages. Make it easier for them to crawl web pages.

  • It is conducive to device analysis, such as the analysis of pages by blind readers. Currently, many Taobao web pages support reading by blind people. This optimization of experience benefits from the good structure and semantics of the web pages. expression.

  • Easy for developers to maintain. Before joining the work, many programmers were in single-person development mode. Single-person development does not matter the code structure, as long as you can understand it. That's almost it. Once you go to work, you will find that your previous bad habits are a bit stretched.

W3C Group working group continues to contribute to web specifications. Their goal is also to stabilize and unify the development trend of the entire Internet. Without further ado, let’s get back to the main point of this article: How to semantically semanticize JavaScript code?

1. First look at the JavaScript code that is difficult to read

1. Judgment

// 数据类型判断
if(Object.prototype.toString.call(str) === “[object String]”){
    // doSomething();
};

// 文件类型判断
if(/.*\.css(?=\?|$)/.test(“/path/to/main.css”)){
    // doSomething();
}
Copy after login

2 . Clear a queue

var Queue = ["test1", "test2", "test3"];
// 常见方式
Queue.length = 0;
Queue = [];
Copy after login

3. Register a variable

// 注册
var repos = {};

repos[“a”] = {
   name: “a”,
   content: {}
};

repos[“b”] = {
   name: “b”,
   content: {}
};
Copy after login

It’s not hard to understand the above examples, the program They are all very simple. In the first example, we use the toString method on the Object prototype chain to determine whether a variable is of string type, and use regular rules to determine whether a file is a css file. The code is relatively easy to write. What if we need to determine whether multiple objects are one of multiple types at the same time? For example, if we need to extract the require dependency from 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 using an empty array to reset this variable are very common methods, but the current scenario is to clear it A queue, can we present it in a more semantic form? For example, what if we only need to clear the first five and last three items of the queue?

In the third example, the registration of variables puts a bunch of registrations together. The above form is indeed clear at a glance. What if a b c d, etc. are separated and interspersed between hundreds of lines of code? Does the sudden appearance of repos["x"] seem a bit unintuitive?

In order to illustrate the ideas advocated in this article, the above explanations are somewhat vague and far-fetched, please read below.

2. Improve the semantics of the code

For the above three cases, use a more semantic way to present the code:

1 . Semantic variable

// 类型判断
function isType(type){
    return function(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([1,2,3]);
isObject({});
Copy after login

I don’t think it needs too much explanation. It seems much fresher compared to

if(Object.prototype.toString.call(str) === “[object String]”){
    // code here...
}
Copy after login

.

// 提取常量
var isCss = /.*\.css(?=\?|$)/;
isCss.test(“/path/to/main.css”);
Copy after login

No matter how long the regular code of isCss is, when we see the word isCss, it is as the name implies. Many people who write regular rules will not extract the regular rules separately and use a meaningful variable to store them. It is okay to add comments . If they do not add comments, subsequent developers will have to bite the bullet and understand the regular rules. To understand the meaning of the code.

Such processing actually increases the amount of code, but looking at it from an engineering perspective can help improve development efficiency and code organization.

2. Semantic behavior

var Queue = ["test1", "test2", "test3"];
Queue.splice(0, Queue.length);
Copy after login

The above code has strong semantics. Starting from the index 0 to the end of the queue, delete all the items in the Queue. item. This way of writing is also more scalable:

Queue.splice(2, 4); // 删除从索引为 2,往后的 4 个元素
Copy after login

This is just a small example. Some behaviors require a lot of code combinations. If there is no good combination of codes for the same behavior, the entire structure will appear very scattered. , not conducive to reading.

// 注册
var repos = [];

function register(o){
   repos[o.name] = o;
}

register({
  name: “a”,
  content: {}
});
Copy after login

Compared with our previous

repos[“a”] = {
   name: “a”,
   content: {}
};
Copy after login

Has the semantic level been improved~

3. Summary

Optimization of the code , there are many dimensions to consider. But code optimization is not about reducing the amount of code. Sometimes we need to add code to improve the readability of the code.

  • Mark variables correctly

  • Encapsulate an action

  • AttentionFunction## How to write

  • #If something is not easy to understand, add comments

The above is the detailed content of How to make JavaScript code more semantic. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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