The Book of Reading Notes series: "Writing maintainable JavaScript" Reading notes (Part One)
The previous article is about the programming style, the record is the most important point, do not talk nonsense, write relatively concise, and this article will add some examples, because it is easier to explain the problem.
Second, the practice of programming
1, UI loosely coupled
First, to remove the CSS from JavaScript (to change the DOM style data, you should manipulate the DOM's class name instead of the DOM's Style property, and later to modify this style only to the corresponding CSS file to modify without modifying the JS file);
Second, to remove JavaScript from the HTML, such as the following writing is not good
<!--bad Writing--
<type= "button" onclick= "dosomething"/>
JS should be placed in the external file, easy to maintain;
Third, avoid the use of CSS expressions, seriously affect page performance;
Take the HTML out of JavaScript, for example, if you want to dynamically generate a table of n rows and 4 columns, the header and the tbody can be written dead on the page, and the body of the table may be generated in such a loop.
// bad wording. var str= ""; for (var i = 0; i < data.length; i++) { str+ = "<tr><td>" + data[i]. Field One + "</td>< Td> "+ data[i]. Field two + " </td><td> "+ data[i]. Field three +" </td><td> "+ data[i]. Field Four +" </td> </tr> "; }; $ ("tbody"). html (str);
If you want to add a field now, the number of columns to increase the table to 5 columns, you have to go to the HTML page to modify the table header, but also to JS to modify the JS file ... So, as far as possible to separate HTML from the JS is good practice, you can write a template in HTML, through the JS get template content substitution variables generated HTML filled into the tbody inside.
2. Avoid using global variables
Naming itself is a difficult thing, if you use a large number of global variables, as the amount of code continues to increase, the probability of naming conflicts increases, and the cost of program maintenance increases.
3. Event handling
Rule 1: Isolate application logic
What do you mean? Like the computer to shut down, there is a shutdown program put in there, you can press the Shutdown button to trigger the shutdown program, you can also click the Start menu and then select Shutdown to trigger the shutdown program, this shutdown program is independent. The same is true of code, when you click the button A or button B to do the same thing, the operation should be written independently as a function, which is the application of logical isolation.
Rule 2: Do not distribute event objects
Look at a piece of code first
function Handleclick (event) { var popup = document.getElementById ("popup"); = Event.clientx + "px"; Popup.style.top= event.clienty + "px"; = "Reveal"; } document.getElementById ("Demo"). onclick=function(event) { Handleclick (event); };
In the above code, the event is distributed in an uncontrolled manner, it passes through the event handler function to Handclick (), and the event object contains a lot of information, while the Handclick function uses only 2 of them, and the function does not indicate what data is necessary. If you want to call this method at this point, you have to create a Evnet object and pass it as a parameter, and you still don't know what information this method uses, we can make the following changes
function Handleclick (x, y ) {var popup = document.getElementById ("popup"); = x + "px"; = y + "px"; = "Reveal"; } document.getElementById ("Demo"). onclick=function(event) { Handleclick (Event.clientx, Event.clienty); };
4, avoid "empty comparison"
Sometimes we need to detect whether a parameter exists for a function, and it is possible to determine whether the parameter exists by determining whether it is equal to null.
var comtroller = { process:function(items) { if(items!== Null) { // bad notation items.sort (); // perform some logic } }}
In this code, the process method obviously wants items to be an array, and then when the value of items is 1 o'clock, which is not equal to NULL, it is still inside the IF statement, and execution to Items.Sort () is an error.
5, detect the original value (string, number, Boolean, undefined, null), typeof is Enough
6, the detection of reference value (object, Array, Date, Error), reference value also known as the object, generally use instanceof to detect whether the object's constructor is the corresponding value can, when cross-frame detection, with instanceof to detect the array will fail, The solution is to call the ToString () method of the object's prototype and determine whether the returned string equals [object Array] to conclude:
// Determines whether value is an array function IsArray (value) { return Object.prototype.toString.call (value) = = = "[Object Array]"; }
7, the detection function with typeof, can be used across frames, return "function", in IE8 and earlier versions of IE, using typeof detection of functions in the DOM node (such as getElementById ()) return "OBJEAC" instead of " function
8. Detection Properties
// bad syntax (Object[propertyname) { // Span style= "color: #008000;" There is a property propertyname // bad notation if (object[propertyname]! = null " // bad notation if (object[ propertyname]! = undefined) { There is a property propertyname }
In the above code, if the property value is False (false, 0, null, undefined) error, the best way to determine whether a property exists is to use the in operator, the in operator simply determines whether the property exists, and does not read the value of the property.
var object = { 0}// good notation if in object) { // The code here will execute }// bad notation if(object["Count" ] { // The code here does not execute }
9. Separating the configuration data from the code
What is configuration data? For example, a page to do an operation failed, need a prompt, and different actions have different prompts, at this time the entire prompt is the configuration data. The configuration data should be separated and passed in as parameters.
10. Throw a custom error throw new error ("Error hint")
When there is an error in code execution, debugging is very difficult if there are no hints or hints that are sparse, obscure, and a custom error is thrown, which is good for debugging where there is a possible error, plus the code that catches the error. Throwing your own error can use the exact text for your browser to display, including the number of rows, functions, and reasons for the failure, which can help you quickly locate the cause of the error.
The ECMA-262 specification identifies 7 types of errors
1) Error: Basic type of all errors
2) Evalerror: throws when executing code error via eval () function
3) Rangeerror: A number is thrown out of its bounds, such as attempting to create an array of length 20 (new Array (-20)).
4) Referenceerror: Thrown when the expected object does not exist, such as attempting to raise a function on a null object reference
5) SyntaxError: syntax error
6) TypeError: Throws an error when the variable is not the expected type
7) Urierror: Throws a malformed URI string to encodeURI (), encodeURIComponent (), decodeURI (), decodeURIComponent (), and other functions
These 7 types of errors need to be memorized.
11, not your object do not move
During the development process, some JavaScript libraries may be referenced, and you are not the authors of these class libraries, but you should follow 3 basic rules
1) No Override method
2) No new method
3) Do not Delete method
12. Browser sniffing
Avoid browser inference
Now there is a more popular way of judging IE browser is
if (document.all) { // ie browser }
This is a browser inference, which concludes that document.all exists only in Internet Explorer, while in fact some versions of opera support document.all
Do feature detection
We know that IE9 and the following IE browser does not support the placeholder property, when we want to give IE9 and the following browsers to simulate the placeholder effect, we need to do the feature detection, if the browser does not support the placeholder attribute to use JS to simulate
if in document.createelement ("input")){ // placeholder not supported, requires impersonation }
The second part ends.
By: Wang Meijian Form:http://www.cnblogs.com/wangmeijian
Original articles, reproduced please indicate the source
Writing maintainable JavaScript reading notes (middle)--programming practice