Home  >  Article  >  Web Front-end  >  12 ways to write high-quality JS code (teach you to write high-quality code)

12 ways to write high-quality JS code (teach you to write high-quality code)

亚连
亚连Original
2018-05-18 17:29:041283browse

This article tells you how to follow 12 methods to write high-quality JS code. Friends who are in need of this can refer to it.

Writing high-quality JS code not only makes programmers comfortable to look at, but also improves the running speed of the program. The following is the editor's method of organizing it:

1. How to write maintainable code

When a bug occurs, it is best if you can fix it immediately. At this time, the four ways to solve the problem are in your mind Still very clear. Otherwise, you move to other tasks or the bug appears after a certain period of time, and you forget that specific code. Looking at the code after a while requires:

1. Spend time learning and understanding 2. The time to solve this problem is to understand the problem code that should be solved

There is another problem, especially for large projects or companies, the guy who fixes the bug is not the person who wrote the code (and the person who discovered the bug and Not the same person fixes the bug). Therefore, it is important to reduce the time it takes to understand code, whether it was code you wrote some time ago or code written by other members of the team. This is about the bottom line (revenue) and developer happiness, because we should be building new and exciting things instead of spending hours and days maintaining legacy code. Therefore, it is crucial to create maintainable code. Generally, maintainable code has the following principles:

Readability

Consistency

Predictability

Looks like it was written by the same person

Recorded

2. Global variables The problem

The problem with global variables is that these global variables are shared by all the code in your JavaScript application and the web page. They live in the same global namespace, so when When two different parts of a program define global variables with the same name but different functions, naming conflicts are inevitable. It is also common for web pages to contain code that was not written by the developer of the page, for example:

Third-party JavaScript library

Advertiser’s script code

Third-party user tracking and analysis script code

Different types of widgets, logos and buttons

For example, this third-party script defines a global variable , called A; then, also define a global variable named A in your function. The result is that the later variables overwrite the previous ones, and the third-party script suddenly becomes invalid! And it's hard to debug it.

Therefore: It is important to use global variables as little as possible, such as namespace mode or functions that are automatically executed immediately, but the most important thing to keep global variables as small as possible is to always use var to declare variables.

3. Forget the side effects of var

There are some small differences between implicit global variables and explicitly defined global variables, which is through delete Operator has the ability to leave variables undefined. The details are as follows:

Global variables created through var (created in any program other than functions) cannot be deleted.

Implicit global variables that are not created through var (regardless of whether they are created in a function) can be deleted.

So implicit global variables are not really global variables, but they are properties of the global object. Attributes can be deleted through the delete operator, but variables cannot. I will not write the specific code.

4. Access the global object

In the browser, the global object can be accessed anywhere in the code through the window attribute (unless you do did something a bit outrageous, such as declaring a local variable named window). But in other contexts, this convenience property might be called something else (or even not available in the program). If you need to access the global object without a hard-coded window identifier, you can do the following in function scope at any level:

var global = (function () { return this; }());

5. for loop

In a for loop, you can loop through the values ​​of arrays or array-like objects, such as arguments and HTMLCollection objects. The usual loop form is as follows:

// Second-best loop for (var i = 0; i < myarray.length; i ) { // Use myarray[i] to do something}

The disadvantage of this form of loop is that the length of the array must be obtained each time it is looped. This reduces your code, especially when myarray is not an array, but an HTMLCollection object.

6. Do not extend the built-in prototype

扩增构造函数的prototype属性是个很强大的增加功能的方法,但有时候它太强大了。增加内置的构造函数原型(如Object(), Array(), 或Function())挺诱人的,但是这严重降低了可维护性,因为它让你的代码变得难以预测。使用你代码的其他开发人员很可能更期望使用内置的 JavaScript方法来持续不断地工作,而不是你另加的方法。另外,属性添加到原型中,可能会导致不使用hasOwnProperty属性时在循环中显示出来,这会造成混乱。

七、避免隐式类型转换

JavaScript的变量在比较的时候会隐式类型转换。这就是为什么一些诸如:false == 0 或 “” == 0 返回的结果是true。为避免引起混乱的隐含类型转换,在你比较值和表达式类型的时候始终使用===和!==操作符。

var zero = 0; if (zero === false) { // 不执行,因为zero为0, 而不是false } // 反面示例 if (zero == false) { // 执行了... }

八、避免eval()

如果你现在的代码中使用了eval(),记住该咒语“eval()是魔鬼”。此方法接受任意的字符串,并当作JavaScript代码来处理。当有 问题的代码是事先知道的(不是运行时确定的),没有理由使用eval()。如果代码是在运行时动态生成,有一个更好的方式不使用eval而达到同样的目 标。例如,用方括号表示法来访问动态属性会更好更简单:

// 反面示例 var property = "name"; alert(eval("obj." + property)); // 更好的 var property = "name"; alert(obj[property]);

使用eval()也带来了安全隐患,因为被执行的代码(例如从网络来)可能已被篡改。这是个很常见的反面教材,当处理Ajax请求得到的JSON 相应的时候。在这些情况下,最好使用JavaScript内置方法来解析JSON相应,以确保安全和有效。若浏览器不支持JSON.parse(),你可 以使用来自JSON.org的库。

同样重要的是要记住,给setInterval(), setTimeout()和Function()构造函数传递字符串,大部分情况下,与使用eval()是类似的,因此要避免。在幕后,JavaScript仍需要评估和执行你给程序传递的字符串:

// 反面示例 setTimeout("myFunc()", 1000); setTimeout("myFunc(1, 2, 3)", 1000); // 更好的 setTimeout(myFunc, 1000); setTimeout(function () { myFunc(1, 2, 3); }, 1000);

使用新的Function()构造就类似于eval(),应小心接近。这可能是一个强大的构造,但往往被误用。如果你绝对必须使用eval(),你 可以考虑使用new Function()代替。有一个小的潜在好处,因为在新Function()中作代码评估是在局部函数作用域中运行,所以代码中任何被评估的通过var 定义的变量都不会自动变成全局变量。另一种方法来阻止自动全局变量是封装eval()调用到一个即时函数中。

考虑下面这个例子,这里仅un作为全局变量污染了命名空间。

console.log(typeof un); // "undefined" console.log(typeof deux); // "undefined" console.log(typeof trois); // "undefined" var jsstring = "var un = 1; console.log(un);"; eval(jsstring); // logs "1" jsstring = "var deux = 2; console.log(deux);"; new Function(jsstring)(); // logs "2" jsstring = "var trois = 3; console.log(trois);"; (function () { eval(jsstring); }()); // logs "3" console.log(typeof un); // number console.log(typeof deux); // "undefined" console.log(typeof trois); // "undefined"

另一间eval()和Function构造不同的是eval()可以干扰作用域链,而Function()更安分守己些。不管你在哪里执行 Function(),它只看到全局作用域。所以其能很好的避免本地变量污染。在下面这个例子中,eval()可以访问和修改它外部作用域中的变量,这是 Function做不来的(注意到使用Function和new Function是相同的)。

(function () { var local = 1; eval("local = 3; console.log(local)"); // logs "3" console.log(local); // logs "3" }()); (function () { var local = 1; Function("console.log(typeof local);")(); // logs undefined

九、编码规范

建立和遵循编码规范是很重要的,这让你的代码保持一致性,可预测,更易于阅读和理解。一个新的开发者加入这个团队可以通读规范,理解其它团队成员书写的代码,更快上手干活。

十、缩进

代码没有缩进基本上就不能读了。唯一糟糕的事情就是不一致的缩进,因为它看上去像是遵循了规范,但是可能一路上伴随着混乱和惊奇。重要的是规范地使用缩进。

十一、注释

你必须注释你的代码,即使不会有其他人向你一样接触它。通常,当你深入研究一个问题,你会很清楚的知道这个代码是干嘛用的,但是,当你一周之后再回来看的时候,想必也要耗掉不少脑细胞去搞明白到底怎么工作的。

Obviously, comments cannot be extreme: each separate variable or a separate line. However, you should generally document all functions, their arguments and return values, or any unusual techniques or methods. Remember that comments can give future readers of your code a lot of clues; readers need (without reading too much) just the comments and function attribute names to understand your code. For example, when you have five or six lines of a program that perform a specific task, the reader can skip this detail if you provide a description of the purpose of the line and why it is there. There is no hard and fast rule about the ratio of comments to code, and some parts of the code (such as regular expressions) may have more comments than code.

12. Curly braces {}

Curly braces (also known as braces, the same below) should always be used, even when they When optional. Technically, braces are not needed if there is only one statement in an in or for, but you should always use them anyway. This makes the code more consistent and easier to update.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

js Summary of the advantages and disadvantages of the three calling methods

Loading within JS jquery.jsDetailed explanation of method

Detailed explanation of JS method for generating random numbers and random sequences in a specified range

The above is the detailed content of 12 ways to write high-quality JS code (teach you to write high-quality code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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