Home > Web Front-end > JS Tutorial > body text

A brief discussion on the coding specifications of JavaScript programming language_Basic knowledge

WBOY
Release: 2016-05-16 18:00:44
Original
2085 people have browsed it

As the most popular client-side scripting language, JavaScript programming language has long been familiar to many web developers. With the advent of the Web2.0 era and the widespread application of Ajax technology, JavaScript is gradually attracting more attention. What is more required at work is in-depth learning of the JavaScript language, flexible application, and guarantee of coding quality.

For engineers who are familiar with C/C or Java language, JavaScript is flexible, simple and easy to understand, and the requirements for code format are relatively loose. It's easy to learn and apply it to your own code. Because of this, JavaScript coding standards are often underestimated and tinkered with during the development process, eventually becoming a nightmare for subsequent maintainers. The long-term value of a software's existence is directly proportional to the quality of its coding. Coding standards can help us reduce unnecessary troubles in programming. The JavaScript code is sent directly to the customer's browser and meets the customer directly. The quality of the coding should be paid more attention to.

This article briefly talks about coding standards in JavaScript programming and analyzes the reasons. It is hoped that more web developers will pay attention to JavaScript coding standards and software product quality issues.

Foreword

When it comes to C/C and Java coding standards, I believe many engineers are familiar with them. But when it comes to the coding standards of the JavaScript language, you may be laughing. Isn’t the syntax of JavaScript very flexible? Variables can be used and declared at any time; statement terminators are not required; strings and numbers can also be added; there will be no error if there are more parameters or less than one. That's right, when you switch from the strict grammatical regulations of C/C and Java to the JavaScript language, you will feel a lot more free and relaxed. Loose syntax is an important feature of JavaScript. It is flexible and easy to understand and brings a lot of convenience to developers, but if you do not pay attention during the writing process, the debugging and maintenance costs of the code will increase invisibly.

JavaScript encoding will be sent directly to the client's browser. Code specifications are not only a guarantee of code quality, but also affect the long-term reputation of the product. I hope that the specification issue of the JavaScript programming language will also attract the attention of more friends.

Recommendations for JavaScript coding standards

This article discusses the layout, naming, declaration, scope, and use of some special symbols involved in the JavaScript coding process, based on personal experience. Summarize the study work, give some of your own suggestions, and analyze the reasons for reference.

JavaScript file reference

JavaScript programs should be placed in .js files as much as possible. When they need to be called, they should be called in HTML with


Such annotations are often seen in JavaScript code. What is the use of a comment like "initialize valueA to be sero"? Couldn't the engineer reading the program see it from the "var valueA = 0;" copy statement? The comment "set timeout to be 20s" is not just for The timing error caused by copying and pasting also misleads the programmer's understanding of this statement. The purpose of the setTimeout () function is not to set the timeout for function execution, but to wait for a certain period of time before executing the called function, which is very harmful. It would be better to delete such comments.

In addition, there are two types of JavaScript comments: "//" and "/* .... */". It is recommended that "//" be used as a code line comment, "/* .... */" " form is used to log out an entire code segment, or in more formal declarations, such as descriptions of function parameters, functions, file functions, etc.

Identifier naming

Naming rules for identifiers in JavaScript:

◆ Use letters, underscore '_' or dollar sign '$' Beginning with

◆ Allow names to contain letters, numbers, underscore '_' and dollar sign '$'

◆ Case sensitive

Variables, parameters, member variables, functions The names of constructors all start with a lowercase letter, and the names of constructors start with an uppercase letter. Variables starting with an underscore '_' are generally used to identify private/local members. Variables starting with the dollar sign '$' are used to identify system-related variables, such as system processes, etc. Avoid naming identifiers with underscore '_' or dollar sign '$'. Reduce the code reading burden as much as possible.

Declaration

Declaration of variables

Although the JavaScript language does not require variables to be declared before they can be used. But we should still develop this good habit. This makes it easier to detect undeclared variables and prevent them from becoming hidden global variables and causing hidden dangers.

At the beginning of the function, you should first use the var keyword to declare the local variables to be used in the function, comment on the function and meaning of the variables, and sort them in alphabetical order. Each variable should be on its own line so you can add comments. This is because in JavaScript only {} of a function indicates scope. Local variables declared with the var keyword are only valid within the function, while variables without var are considered global variables. Let's take a look at Listing 3.

Listing 3. Local variable declaration

Code:
Copy code The code is as follows:



From the output of the above example, we were surprised to find that there is a difference between the variable valueA declared with var and the undeclared variable valueB. It is particularly important to note that variables declared with var inside a function are local variables, which can effectively avoid errors caused by local variables and global variables having the same name.

Declaration of functions

Functions should also be declared before calling. Internal functions should be declared after the var statement declaring internal variables, which can clearly indicate the internal variables and The scope of the inner function.

In addition, the function name must be immediately between the left bracket '(', and there should be a space between the right bracket ')' and the following '{' to clearly display the function name and its parameter part. and the beginning of the function body. If the function is an anonymous/nameless function, there must be a space between the function keyword and the left bracket '(', otherwise it may be mistaken that the function name is function.

Listing 4. Internal function Declaration

Code:
Copy code The code is as follows:



As can be seen from the output of Listing 4, the inF () function only takes effect inside the outF () function, and the local variable innerA takes effect in the scope of the inner function. The coding method makes the scope of variables and functions clear. At the same time, there is at most one statement in one line. If an assignment statement uses functions and objects to assign values, it may need to span multiple lines. Be sure to add a semicolon at the end of the assignment statement. This is because in JavaScript, All expressions can be used as statements. When a newline character is encountered, it will be parsed as the end of the expression. At this time, irregular line breaks and the loss of semicolons may introduce new errors.

For compound statements, if, Code bodies such as for, while, do, switch, try...catch, function body of function definition, object definition, etc. need to be placed inside curly braces '{}'
◆ '{' should be at the end of the line. , marks the beginning of the code block.

◆ '}' should be at the beginning of a line, marking the end of the code block, and needs to be aligned with the beginning of the line where '{' is located, to indicate a complete compound statement segment. It can greatly improve the readability of the code, and the control logic can be clearly displayed.

◆ The included code segment should be indented by 4 spaces. Even the included code should be indented. If a paragraph has only one sentence, it should be included with curly braces '{}'. Although it is not wrong to code without curly braces, if you need to add statements, it is easier to cause compilation errors or logic errors due to omission of curly braces.

The return statement also needs to be used with caution. If the execution of an expression is used as the return value, please put the expression and return on the same line to avoid the newline character being misinterpreted as the end of the statement and causing a return. mistake. If there is no return expression after the return keyword, undefined is returned. The default return value of a constructor is this.


Listing 5. return expression


Code:




Copy code
The code is as follows:





Listing 5 shows the return error caused by the return expression not being placed on the same line as the return keyword, which needs attention.

Special symbols

Blank characters

Appropriate blank lines can greatly improve the readability of the code and make the code The logic is clearer and easier to understand. At the same time, leaving appropriate blanks in expressions will also make it easier to read the code.

If there are brackets after the keyword, it is best to leave a blank space between the keyword and the left bracket '(', such as for, if, while, etc. It is not appropriate to leave a blank space between the function name and the brackets. But if it is an anonymous function, you must leave a blank between function and the left bracket '(', otherwise the editor will mistakenly think that the function name is function.

In expressions, binary operators (except left It is best to leave a blank space between the bracket '(', the left square bracket '[', and the scope point '.') and the two operands. It is not appropriate to leave a blank space between the unary operator (if it is not a word typeof, etc.) and its operand. .

There needs to be a blank space after the comma ',' to show clear parameter intervals, variable intervals, etc.

The semicolon ';' usually indicates the end of the expression statement, and should be empty. OK. In the conditional statement of for, there should be a blank space after the semicolon.

{ } and [ ]

In JavaScript, it is usually natural to define empty objects and empty arrays. I think of using new Object () and new Array (). In fact, curly brackets '{}' and square brackets '[]' can be used directly to define an empty object and an empty array. This writing method can make the code more readable. It seems simple and easy to understand.

== and ===

are common things in code, but JavaScript is different from other well-known programming languages. In addition to using two equal signs '==' to make judgments, you can also use three equal signs '===' to make logical equality judgments. The difference between the two is that '==' will make logical equality judgments. Perform type conversion first and then compare. '===' does not. Therefore, the difference between '!=' and '!==' may be different. Try to use '===' to judge logical equality, and use '!==' to judge logical inequality.

Listing 6. Use of ===

Code:
Copy code The code is as follows:



Listing 6 In , the values ​​of the two variables valueA and valueB are obviously not equal. At least valueA is a string and valueB is a number. But when using '==' to make a judgment, the program outputs equal words. This is because when the compiler compares two variables, because their types are different, it automatically converts valueB into a string, and then compares it with valueA. The judgment result obtained by using '===' is consistent with the expected result.



The plus sign ' ' is also one of the operators well-known to programmers. The difference between JavaScript and other programming languages ​​is that in JavaScript, in addition to adding numeric values ​​and concatenating strings, ' ' can also be used as a unary operator to convert strings into numbers. Therefore, if used improperly, it may be confused with the auto-increment symbol ' ' and cause calculation errors. This can be clearly seen in Listing 7.

Listing 7. Clever number

Code:
Copy code The code is as follows:




Summary

This article discusses the layout, naming, declarations, statements, and some special characters of JavaScript code In terms of usage, etc., he talked about his suggestions on JavaScript programming standards. In addition, there are many aspects that require in-depth understanding and study, such as the use of with, eval statements and this objects, etc. While we understand its universality, we also need to pay attention to its particularity and pay more attention when writing code to create more and better program codes.
Related labels:
source:php.cn
Previous article:Use dtree to implement tree menu dtree usage instructions_navigation menu Next article:The difference between childNodes in IE and FireFox_javascript skills
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
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template