Home Web Front-end JS Tutorial JavaScript Coding Standards Recommended_Basic Knowledge

JavaScript Coding Standards Recommended_Basic Knowledge

May 16, 2016 pm 05:53 PM
Coding Standards

1. Naming
1. Give variables and functions a meaningful name, do not name them randomly.
2. Non-constructor functions use camel case naming, and try to use a verb-object structure to distinguish them from variable names, such as getName or IsFull. The first letter of the constructor (that is, a custom type) name is capitalized to distinguish it from non-constructor functions, such as Person.
3. Variables use camel case naming. Since JavaScript is a weakly typed language, it is recommended to prefix the variable name: integer (i), floating point number (f), boolean (b), string (s), array (a). But it is not mandatory to do this. You can choose according to your personal preferences. Once you have made the choice, do not mix the two methods of adding prefixes and not adding prefixes.

2. Layout
1. Space.
a) Leave a space between var and the variable name, a space between the variable name and the equal sign, a space between the equal sign and the initial value, and no space between the initial value and the semicolon. For example: var i = 10;
b) When using literals to declare reference type variables, leave no spaces between each attribute and the colon, and leave a space between the colon and the initial value. For example:
Copy code The code is as follows:

var Person = {
age: 16 ,
name: "Sam"
};

c) Leave a space between function and function name, no space between function name and (), () and { Leave a space between them.
d) Leave a space between each parameter of the function.
e) Leave a space between if, while, for and the left bracket to emphasize the keyword; leave no space between switch, with and the left bracket.
f) Leave a space between the binary operator and the left and right operands. When a line of code is long, no spaces can be left.
2. Line break.
a) Each statement occupies one line. Do not use multiple statements on one line.
b) The braces { after block-level scopes such as if, while, for, etc. do not start on a new line, just put them on the same line as the keywords.
3. Indent.
a) Use 4 spaces for indentation and do not use tabs.
b) When the scopes are different, they should be indented to show their hierarchical relationship.

3. Comments
1. Add comments appropriately. Comments cannot be completely absent, nor are the more the better. Just add comments to important methods, variables, and algorithms (or other issues that need attention).
2. When modifying the source code, you need to modify the comments simultaneously to keep them consistent.
3. Do not use html comments in the code.

4. Specifications
1. The var keyword must be added when declaring variables. Although JavaScript allows the var keyword to be omitted and become a global variable, this is a source of problems.
2. When declaring a variable, it must be initialized at the same time. It is best not to change the data type of the variable later.
3. If a semicolon can be added at the end of the statement, it must be added.
4. If, while, for, etc. have only one statement, they also need to be placed within braces.
5. Do not use global variables arbitrarily. If you have to use them, it is best to use only one global variable.
6. JavaScript should be loosely coupled with html and css. HTML is the data layer, CSS is the presentation layer, and JavaScript is the behavior layer. Tight coupling between the three should be avoided, otherwise it will be difficult to maintain later. There should be no specific JavaScript code in html, and all external files should be included; in JavaScript, try not to use innerHTML to insert a large number of html elements. You should consider placing elements in html, but just hide them initially; do not directly use JavaScript To modify specific properties in css, you should modify them indirectly through className.
7. Do not modify objects that are not owned by you, do not add properties or methods to their instances or prototypes, and do not repeatedly define their existing methods. Otherwise, potentially subtle problems could result when a new version of the object adds a property or method with the same name. There are two solutions: one is inheritance and the other is inclusion.
8. Use namespaces to prevent conflicts between multiple libraries. Please refer to the organization of the YUI library.
9. For literals that appear in the code, they should be placed in the attribute of a variable, with the first letter of the attribute name or all letters capitalized (simulating define or enum in other languages). For example:
Copy code The code is as follows:

var Color = {
RED: 1 ,
BLUE: 2,
GREEN: 3
};

10. 함수에 전달된 매개변수를 확인하세요. 기본 유형인 경우 typeof를 사용하고, 참조 유형인 경우 objectof를 사용하고, 객체에 메소드가 포함되어 있는지 확인하려면 해당 메소드에 typeof 연산자를 사용하고 이를 "undefine" 문자열과 비교하세요.

5. 성능
1. 글로벌 검색을 피하세요. 전역 변수 및 함수를 사용하는 것은 지역 변수 및 함수를 사용하는 것보다 비용이 더 많이 듭니다. 전역 변수 및 함수에는 범위 체인 조회가 포함되기 때문입니다. 따라서 함수 내에서 전역 변수를 여러 번 사용하는 경우에는 여러 번 범위 체인 검색을 수행하여 이러한 문제를 방지하기 위해 여러 번 사용된 전역 변수를 지역 변수에 할당하고 해당 지역 변수를 사용하게 됩니다. 미래에.
2. 마녀 표현을 사용하지 마세요. with 문은 자체 범위를 생성하므로 추가 오버헤드가 발생합니다.
3. 속성 조회를 피하세요. 속성 조회는 O(n) 작업이며 객체에 대한 모든 속성 조회는 변수 및 배열에 액세스하는 것보다 시간이 더 걸립니다(변수 및 배열에 액세스하는 것은 O(1) 작업입니다). 따라서 동일한 속성을 여러 번 사용하는 경우에는 로컬 변수에 저장해야 합니다. 예:
코드 복사 코드는 다음과 같습니다.

var sUrl = window.location .href;
var sData = sUrl.substring(sUrl.indexOf("?"))
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Sharing tips on dealing with the problem of Chinese garbled characters imported into Oracle Sharing tips on dealing with the problem of Chinese garbled characters imported into Oracle Mar 09, 2024 pm 10:03 PM

Tips for dealing with Chinese garbled characters imported into Oracle. During the process of data import using Oracle database, we often encounter garbled Chinese data. This may be due to character set mismatch, data source encoding issues, or database configuration errors. In order to solve this problem, this article will share some tips for dealing with the problem of Chinese garbled characters imported into Oracle, so that everyone can smoothly import Chinese data in actual operations. 1. Check the database character set. Before dealing with the Chinese garbled problem, you first need to check

Python Development Notes: Avoid Common Coding Mistakes Python Development Notes: Avoid Common Coding Mistakes Nov 22, 2023 pm 05:18 PM

Python is a popular programming language that is becoming more and more popular in the field of software development. However, due to the characteristics of the Python language, some coding errors sometimes occur. This article will introduce some common Python coding errors and ways to avoid these errors, hoping to help developers write better Python code. Use the appropriate encoding method Python supports multiple encoding methods, such as UTF-8, UTF-16, GB2312, etc. When writing code, make sure you select the appropriate

Detailed explanation of Go language comment encoding specifications Detailed explanation of Go language comment encoding specifications Mar 23, 2024 pm 09:54 PM

Detailed explanation of Go language comment coding specifications In programming, comments are a very important coding specification, which can help other developers understand the meaning and logic of the code. Especially for team development, standardized comments can improve the readability and maintainability of the code. This article will introduce the comment coding specifications in the Go language in detail, and provide specific code examples to show how to write comments in a standardized way. 1. Single-line comments In Go language, single-line comments start with // and are followed by the comment content. Single-line comments are mainly used to comment on a certain line of code.

Handwritten PHP API Framework (1) PSR Specification Handwritten PHP API Framework (1) PSR Specification Feb 10, 2023 am 10:31 AM

This article brings you relevant knowledge about PHP. It mainly talks about coding standards with you. It is also recommended that you try to follow the standards during development. Friends who are interested can take a look below. I hope it will be helpful to you. .

C++ Development Notes: Avoid Coding Standard Issues in C++ Code C++ Development Notes: Avoid Coding Standard Issues in C++ Code Nov 22, 2023 am 08:35 AM

When developing in C++, in addition to focusing on issues such as function implementation and performance optimization, developers also need to pay attention to the coding specifications of the code. Good coding practices not only improve code readability and maintainability, but also help reduce errors and increase code consistency. This article will introduce some common C++ development considerations to help developers avoid coding standard problems. Use meaningful naming: Variables, functions, and classes should be named to accurately reflect their purpose and functionality. Avoid using single letters or meaningless abbreviations as names

Discussion on the underlying development principles of PHP: coding standards and best practices Discussion on the underlying development principles of PHP: coding standards and best practices Sep 08, 2023 pm 12:37 PM

Discussion on the underlying development principles of PHP: Coding standards and best practices Introduction: PHP is a very popular server-side programming language, and its underlying development principles are very important for developers. This article will delve into the coding standards and best practices for underlying PHP development, and deepen understanding through code examples. 1. Coding standards and unified code style In the underlying development of PHP, it is very important to maintain the unity of code style, which can improve the readability and maintainability of the code. Use a common coding style specification, such as PSR-2,

Python Best Practices: A Guide to Safe Coding Practices Python Best Practices: A Guide to Safe Coding Practices Jun 30, 2023 pm 12:25 PM

Introduction to Python's best practices in secure coding specifications With the rapid development of the network and the popularity of the Internet, secure coding has become a crucial link in software development. Along the way, developers need to use some best practices to ensure the code they write is secure. Python is a popular programming language that is widely used for web application and system development. In Python applications, developers need to pay attention to some common security issues and follow some secure coding practices to prevent potential

Understand the underlying development principles of PHP: coding standards and best practice guidelines Understand the underlying development principles of PHP: coding standards and best practice guidelines Sep 11, 2023 pm 06:05 PM

Understand the underlying development principles of PHP: Coding standards and best practice guidelines In today's web development field, PHP, as a widely used scripting language, is chosen as the tool of choice by many developers. However, for many PHP developers, understanding the underlying development principles of PHP and how to write standardized code can be a challenge. This article will introduce some basic principles of PHP underlying development, as well as coding standards and best practice guidelines to help readers improve the efficiency and quality of PHP development. 1. PHP underlying development principles PHP

See all articles