


12 ways to write high-quality JS code (teach you to write high-quality code)
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

WeChat is one of the mainstream chat tools. We can meet new friends, contact old friends and maintain the friendship between friends through WeChat. Just as there is no such thing as a banquet that never ends, disagreements will inevitably occur when people get along with each other. When a person extremely affects your mood, or you find that your views are inconsistent when you get along, and you can no longer communicate, then we may need to delete WeChat friends. How to delete WeChat friends? The first step to delete WeChat friends: tap [Address Book] on the main WeChat interface; the second step: click on the friend you want to delete and enter [Details]; the third step: click [...] in the upper right corner; Step 4: Click [Delete] below; Step 5: After understanding the page prompts, click [Delete Contact]; Warm

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement
