In the process of writing and using the JS program, we often encounter a variety of errors, for a browser-dependent language, it is difficult to fully control its right at any time the correct operation. But we still have to make our own efforts to enhance our written JS program code robustness and security, as far as possible to reduce the likelihood of error.
The following is a summary of my Learning JS process to enhance the robustness of the JS program, if you think that you have a little value, then I achieve their purpose, if you feel that there is no meaning, please do not throw bricks, thank you.
(1) for the necessary parameters to determine whether the correct incoming.
code example:
<script language= "JavaScript" type= "Text/javascript" > <!--function Getarg (ARG) {//To determine if an element exists if (AR g==undefined) {alert (' Hint: A parameter must be passed in! '); return; Alert (' parameter is: ' +arg); } getarg ("ABCDE") Getarg (); --> </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
(2) different processing depending on the type of parameter passed in:
For example, when we want to get an HTML element object, we need to determine whether an ID or an element object is passed in.
code example:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <ptml xmlns=" http://www.w3.org/1999/xhtml "> <pead> <title> New Document </title> <meta name= "generator" content= "EditPlus"/> <meta name= "author" content= ""/> <meta name= "Keywor DS "content=" "/> <meta name=" description "content=" "/> </pead> <body> <div id=" a "&G T;area a</div> <div id= "B" >area the b</div> <script "JavaScript" language= "type=" > <!--function getinnerhtml (elm) {//elm for an incoming HTML element object or ID//judge incoming time element ID or object var obj=typeof (elm) = "s Tring "document.getElementById (Elm): Elm; Determine if the element exists if (!obj) {alert (' incoming object does not exist! Please check! '); Return ""; return obj.innerhtml; Alert (getinnerhtml ("a")); Alert (getinnerhtml (document.getElementById ("B"))); Alert (getinnerhtml ("C")); --> </script> </body> </ptml>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
(3) Set the default value for the parameter.
<script language= "JavaScript" type= "Text/javascript" > <!--function Defaultarg (ARG1,ARG2) {//Assume parameters can only be characters The situation of the string var arg1=arg1| | " Default Arg1 "; var arg2=arg2| | " Default Arg2 "; Alert (arg1+ "," +arg2); } defaultarg (); Pop-up content is: "Default Arg1,default arg2" Defaultarg ("my Arg1"); Pop-up content is: "My Arg1,default arg2" Defaultarg ("My Arg1", "my Arg2"); Pop-up content is: "My arg1,my arg2"//--> </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
(4) Check the incoming parameter types.
For example:
We require that a parameter passed in must be a number.
Sample code:
<script language= "JavaScript" type= "Text/javascript" > <!--function Checkarg (arg1,arg2) {if (arg1==u ndefined) {alert (' Arg1 must initialize! '); Return } if (typeof (Arg1)!= "number") {alert (' arg1 must be numeric! '); Return Alert (' parameter valid '); } checkarg (); The pop-up reads: "Arg1 must be initialized!" Checkarg ("SSS"); The pop-up reads: "Arg1 must be a number!" Checkarg (5); Popup content: "parameter is valid"//--> </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
Again, for example, we might need to set a width or height value by using the parameter:
Sample code:
<script language= "JavaScript" type= "Text/javascript" > < !--//In HTML pages, we usually set the width of the value of less than 1000 (1-3 digits) or a percentage of the function SetWidth (w) {var width= "300px"; Allow 1-3 digits and percent if (/^\d{1,3}$/.test (W)) {width=w+ "px"; }else if (/^ (\d{1,2}%) |100%$/.test (W)) {width=w; }else {alert ("Set width value is not valid!) will use default settings "); Alert ("The width value you entered is:" +width); } setwidth (100); Legal value setwidth (2500); More than 1000, illegal setwidth ("ddd"); String, illegal setwidth (); SetWidth not passed in ("80%"); Percentage, legal value setwidth ("1000%"); Greater than 100%, illegal//--> </script>
[ctrl+a All selected note: If you need to introduce external JS need to refresh to perform]
(5) in JS OO programming, if the program is to get the current instance name, you must make a judgment on the incoming instance name.
Sample code:
<script language= "JavaScript" type= "Text/javascript" > <!--var inscounter=0; Identifies different instance function Getinsname (insname) {this.__id__= "sign-" +inscounter++; The current instance identifies this.__insname__=insname; this.__initalize__=0; Have you done a parameter check}//parameter Validation getinsname.prototype.__init__=function () {if (!this.__insname__) {alert (' Hint: initialization lost Defeat! Please pass in the instance name '); return; The try{//Incoming instance name is not an instance of this object, or the same instance name is set for two instances, and an error message if (!eval this.__insname__+ instanceof Getinsname ")|| Eval (this.__insname__+ ". __id__")!=this.__id__) {//Incorrect instance name alert ("Hint: Initialization failed!") Please set the correct instance name "); return; }}catch (e) {//If the Passed-in instance name does not exist, the above eval (this._insname) will cause an error//Non-existent Instance name alert ("Hint: initial The failure of! The instance name you have set does not exist, please reset "); return; } this.__initalize__=1; return true; } GetInsName.prototype.someMethoD=function () {if (!this.__initalize__&&!this.__init__ ()) {return;} Alert ("The Passed-in instance name is correct!") "); var tempvar= "Test"; A temporary variable var ins1=new getinsname (); var ins2=new getinsname ("TTT"); Nonexistent instance name Var ins3=new getinsname ("Ins2"); Instance name Var ins4=new getinsname ("TempVar")//non-instance name var ins5=new getinsname ("Ins5") of this object; Ins1.somemethod (); Ins2.somemethod (); Ins3.somemethod (); Ins4.somemethod (); Ins5.somemethod (); --> </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
(6) First check the incoming XML data type (Dom?) before parsing the XML data. XML string? File name) and the legality of its structure.
Sample code:
<script language= "JavaScript" type= "Text/javascript" > <!--function Loadxml (XML) {if (window). ActiveXObject) {var xmldom=new activexobject ("Microsoft.XMLDOM"); }else{if (document.implementation&&document.implementation.createdocument) {VA R xmldom=document.implementation.createdocument ("", "Doc", NULL); }} Xmldom.async=false; Xmldom.preservewhitespace=true; Loaded as an XML file and then loaded as an XML string if (!xmldom.load (XML)) {try{xmldom.loadxml (XML); }catch (e) {//non IE browser var oparser=new domparser (); Xmldom=oparser.parsefromstring (XML, "Text/xml"); } return xmldom; function Parsexml (XML) {if (!xml) {alert (' Please set XML data '); return; var xmldom=typeof (XML) = = "Object"?Xml:loadxml (XML); Determines whether an object or a string (string includes an XML data string or file name) if (!xmldom.documentelement) {alert ("Hint: illegal XML data!") "); return; Alert ("Legitimate XML data!") "); var xmldom=loadxml ("<t><c>dom</c></t>"); Parsexml (); Data Parsexml not set ("<d><t>test</t></d>"); Incoming legal XML Data Parsexml ("<d><t></d>"); Incoming illegal XML data parsexml (XMLDOM); Incoming DOM type data//parsexml ("Data.xml")//Incoming XML file//--> </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
(7) The use of Try...catch statements, many times the error we can not be shielded, using Try...catch it is easy to filter out these errors.
For example, when we use UserData, many browsers do not support, using Try...catch can simplify our processing.
<script language= "JavaScript" type= "Text/javascript" > <!--try{//userdata operation Object Datacontainer=docu Ment.documentelement; Datacontainer.addbehavior ("#default #userdata"); Alert (' Can manipulate userdata data '); }catch (e) {alert (' Do not support UserData, perform other actions '); }//--> </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
You are welcome to comment more and make better suggestions.
arg==undefined to arg = = undefined may be better
var arg1=arg1| | " Default Arg1 ";
That's a little bit of a problem.
Arg1 is null 0 "" False is not
<script language= "JavaScript" type= "Text/javascript" > <!--alert (null==undefined); alert (null===undefined); --> </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
The three equals sign represents the same type. JS does not automatically convert the type when compared.