Read "Writing high-quality code: 188 Recommendations for improving JavaScript programs" 1

Source: Internet
Author: User

Recommendation 3: Reduce global variable contamination

There are 3 ways to define global variables:? Executes the Var statement directly outside of any function. var f= ' value ';? Adds an attribute directly to the global object. A global object is a container for all global variables. In a Web browser, the global object is named window. window.f= ' value ';? Using undeclared variables directly, the global variables defined in this way are called implicit global variables. f= ' value '; To make it easy for beginners to intentionally design an implicit global variable without declaring a variable before use, unfortunately forgetting to declare a variable is a very common phenomenon. The strategy of JavaScript is to make the variables that are forgotten to be declared as global variables, which makes it very difficult to find bugs in the program. The worst part of the JavaScript language is its dependence on global variables. A global variable is a variable that is visible in all scopes. Global variables can be handy in very small programs, but as programs become larger, it quickly becomes difficult to handle. Because a global variable can be changed by any part of the program at any time, the behavior of the program is greatly complicated. The use of global variables in programs reduces program reliability. Global variables make it harder to run separate subroutines in the same program. If the names of some global variables are the same as the variable names in the subroutine, they will conflict with each other and may cause the program to fail, and often make the program difficult to debug. In fact, these global variables weaken the flexibility of the program and should avoid using global variables. Try to reduce the way you use global variables: Create a unique global variable in your application and define the variable as the container for the current application. var my={}; my.name={"First-name": "First", "Last-name": "Last"}; My.work={number:123,one:{name: "One", Time: "2012-9-14 12:55", City: "Beijing"},two:{name: "One", Time: "2012-9-12 12:42 "City:" Shanghai "}; As long as multiple global variables are appended to a namespace, the probability of collisions with other applications is significantly reduced, and the application becomes easier to read because my.work points to the top-level structure. Of course, the closure can be used to hide information, it is another effective way to reduce "global pollution". In programming languages, scopes control the visibility and life cycle of variables and parameters. This provides an important help for program development because it reduces name collisions and provides automatic memory management. var foo=function () {var a=1,b=2;var bar=function () {varB=3,c=4;//a=1,b=3,c=4a+=b+c;//a=8,b=3,c=4};//a=1,b=2,c=undefinedbar ();//a=21,b=2,c=undefined}; Most languages that use C-language syntax have block-level scopes. For a block of code, a statement that is included in a pair of curly braces, where all the variables defined are not visible outside the code block. The variables defined in the code block are freed after the code block executes. However, for the JavaScript language, although the language supports the syntactic form of a block of code, it does not support block-level scopes. JavaScript supports function scopes, and the parameters and variables defined in the function are not visible outside the function, and variables defined anywhere in a function can be seen anywhere in the function. Other mainstream programming languages recommend declaring variables as late as possible, but not in JavaScript, because it lacks block-level scopes, and it's a good idea to declare all the variables that might be used in a function at the top of the function body.

Recommendation 4: Note the specificity of JavaScript data types

1The floating-point number that prevents floating-point overflow binary cannot correctly handle decimal decimals, so 0.1+0.2 Not equal to 0.3. Num=0.1+0.2;//0.30000000000000004This is the most frequently reported bug in JavaScript, and this is followed by a binary floating-point arithmetic standard (IEEE754) and the resulting results. This standard is suitable for many applications, but it violates the basic knowledge of numbers. Fortunately, integer arithmetic in floating-point numbers is accurate, so the problem with decimals can be avoided by specifying the precision. For example, the addition of the above can be handled like this: a= (1+2)/10;//0.3This processing is often used in currency calculations and, of course, is expected to be accurate when calculating the currency. For example, the meta can be multiplied by 100 and all of the components, and then you can accurately add each item, the sum of the results can be divided by 100 to convert back to the element. 2. It is an implicit behavior to use the JavaScript type to automatically convert data types in JavaScript that automatically convert variables. When converting data types automatically, JavaScript generally follows: If a value of a type is used in an environment that requires other types of values, JavaScript automatically converts this value to the desired type, as shown in table 1.1. If a non-empty object is used in a logical operation environment, the object is converted to true. The object at this time includes all types of objects, even if the wrapped object with a value of false is also converted to true. If the object is used in a numeric operation environment, the object is automatically converted to a number, and if the conversion fails, the return value is Nan. When an array is used in a numeric operation environment, the array determines the value of the transformation based on the contained element. If the array is an empty array, it is converted to the numeric value 0. If the array contains only one number element, it is converted to the numeric value of the number. If the array contains multiple elements, or contains only one non-numeric element, Nan is returned. When the object is used in a string environment, JavaScript can call the ToString () method to convert the object to a string and then perform the related calculations. When an object is associated with a numeric value, an attempt is made to convert the object to a numeric value and then participate in the sum operation. If the object cannot be converted to a valid numeric value, the string join operation is performed. 3. Correct detection of data types use the TypeOf operator to return a string that identifies the type of operand. For any variable, using the TypeOf operator always returns one of the following 6 types as a string:?"Number"?"String"?"Boolean"?"Object"?"Function"?"Undefined"Unfortunately, when using typeof to detect null values, the return is "object" instead of "NULL". A better way to detect null is actually very simple. The following defines a general method for detecting a value type:functiontype (o) {return(o===NULL)?" Null ":(typeofo);} This avoids the type detection because the null value affects the base data. Note: TypeOf is not able to detect complex data types, as well as various special purpose objects such as regular expression objects, date objects, mathematical objects, and so on. For an object or an array, you can use the constructor property, which refers to the function that originally constructed the object. If you combine the typeof operator with the constructor property, you can basically perform the detection of the data type. The test results for different types of data are shown in table 1.2. 

Recommendation 6: Correctly handle JavaScript special values

2. There are 5 basic types of correct use of NULL and Undefinedjavascript: String, number, Boolean, NULL, and undefined. The first 3 kinds are better understood, the latter two kinds are slightly more complicated. A null type has only one value, that is, the null;undefined type has only one value, which is undefined. Both null and undefined can be used directly in JavaScript code as literals. Null is associated with an object reference, which represents an object reference that is either empty or nonexistent. When a variable is declared without assigning a value to it, its value is undefined. The value of undefined will appear in the following cases:? Gets a property from an object that has a value of undefined if the object and its prototype chain do not have the property. If a function does not explicitly return a return value to its caller through a return statement, the return value is undefined, except when the function is called with new. JavaScript functions can declare any number of parameters, when the function is actually called, if the number of arguments passed is less than the number of formal parameters declared, then the value of the extra formal parameter is undefined. If you use typeof detection for a variable that has a value of NULL, the result is "object" and the value of typeof undefined is "undefined". NULL==undefined,NULL!==undefined. Unlike null, undefined is not a reserved word for JavaScript, and undefined is defined as a global variable in the ECMAScript V3 standard, with an initial value of undefined. Therefore, there is a compatibility problem when using the undefined value (the earlier browsers may not support undefined). In addition to the direct assignment and the use of the typeof operator, any operator operation on undefined throws an exception. However, you can declare the undefined variable and then view its value, if its value is undefined, which means the browser supports undefined values. For example:varUndefined;alert (undefined); If the undefined keyword is not supported by the browser, you can customize the undefined variable and assign it a value of undefined. For example:varUndefined=void NULL, declaring the variable to be undefined, initializing it to the value of the expression void null, because operator void ignores the result value of the expression when the expression is executed, and always returns the value undefined, Therefore, this method can be used to define a variable as undefined and assign it to undefined. Since the variable undefined is assigned a value of undefined, you can also use the following method:varUndefined=void1, or use a function with no return value:varUndefined=function() {} (); alert (undefined);//"undefined"You can use the TypeOf operator to detect whether a variable has a value of undefined:varA;if(typeofa== "Undefined"){}3The type system using pseudo-value JavaScript is very chaotic, the type characteristics are not obvious, and the crossover is confusing. The JavaScript syntax system has a large set of false values, as shown in the following code. The Boolean value of these values is false. 0// NumberNaN// Number‘‘//Stringfalse//BooleanNULL//Objectundefined//UndefinedThese values are all equal to false, but they are not interchangeable. For example, the following usage is incorrect. Value=Myobject[name];if(value==NULL{} This is the wrong way to determine whether an object is missing a member property. Undefined is a missing member property value, and the above code fragment is tested with NULL, using a type that enforces the conversion of the= = operator, not more reliable = = =operator. The correct usage is as follows: Value=Myobject[name];if(!value) {}undefined and Nan are not common, they are global variables, they can also change their values, although this should not be done in programming, but they can be changed. 

Read "Writing high-quality code: 188 Recommendations for improving JavaScript programs" 1

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.