Home > Web Front-end > JS Tutorial > How to write quality JS code

How to write quality JS code

亚连
Release: 2018-06-13 14:21:06
Original
1351 people have browsed it

This article tells you how to follow 12 methods to write high-quality JS code. Friends who need this convenience 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. Here is how I organize it:

1. How Writing 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 still very clear in your mind. 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. Problem with global variables

The problem with global variables is that all code in your JavaScript application and web pages share these global variables. They live in the same global namespace, so when two different parts of the program define the same name but different functions When using global variables, 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 users Track and analyze script code

Different types of widgets, logos and buttons

For example, the third-party script defines a global variable called A; then, in your function Define a global variable named A. 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 from 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 the function scope at any level:

var global = (function () { return this; }());
Copy after login

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

Amplifying the prototype attribute of the constructor is a very powerful way to increase functionality, but sometimes it Too strong. It's tempting to add built-in constructor prototypes (such as Object(), Array(), or Function()), but this seriously reduces maintainability because it makes your code unpredictable. Other developers who use your code will probably prefer to use the built-in JavaScript methods to work continuously, rather than the methods you add. In addition, properties added to the prototype may cause it to be displayed in the loop when the hasOwnProperty attribute is not used, which can cause confusion.

七、避免隐式类型转换

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"
Copy after login

另一间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
Copy after login

九、编码规范

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

十、缩进

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

十一、注释

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

很显然,注释不能走极端:每个单独变量或是单独一行。但是,你通常应该记录所有的函数,它们的参数和返回值,或是任何不寻常的技术和方法。要想到注 释可以给你代码未来的阅读者以诸多提示;阅读者需要的是(不要读太多的东西)仅注释和函数属性名来理解你的代码。例如,当你有五六行程序执行特定的任务, 如果你提供了一行代码目的以及为什么在这里的描述的话,阅读者就可以直接跳过这段细节。没有硬性规定注释代码比,代码的某些部分(如正则表达式)可能注释 要比代码多。

十二、花括号{}

Curly braces (also called braces, the same below) should always be used, even when they are 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:

How to use vue to implement permission management functions

How to use http-proxy in webpack-dev-server ( Detailed tutorial)

How to implement recursive tree menu component in vuejs (detailed tutorial)

How to use echarts in vue

The above is the detailed content of How to write quality JS code. 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