Home  >  Article  >  Web Front-end  >  Learn to be stingy with javascript and streamline your code_javascript skills

Learn to be stingy with javascript and streamline your code_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:28:541056browse

1. Be stingy with your code and use the least code to do the most appropriate thing;
For example, if your code uses a lot of document.getElementById(), have you considered writing a simple ID selector

Copy code The code is as follows:

function $(Id)
{
return document.getElementById(Id ; Refactor?
For example, if you already have a complete form regularity verification framework, and one day you find that a certain form cannot find the corresponding regularity in the serious framework, your possible approach is to simply add an if to achieve it, but why Why not extend a regular expression in the validation framework to keep the code clean?
, Stingy code execution steps
For example, when we write ajax code, we often write the following code:




Copy code
The code is as follows: var xmlObject; function createXMLHTTPRequest()
{
if(window.ActiveXObject)
{  
xmlObject = new ActiveObject( "Microsoft.XMLHTTP");
}
else
{ ​
xmlObject = new XMLHTTPRequest();
}
}


But every time we generate An object needs to be judged once. Why not remember it after generating the object for the first time and just create new next time? The improved code is as follows



Copy code
The code is as follows: var _ajax = function(){ _self = this;
}
_ajax.prototype = {
/**
* Build http request object
*/
_create: function(){
var factories = [
function() {return new XMLHttpRequest();}, //Non-IE series
function(){return new ActiveXObject("Microsoft.XMLHTTP");}, //IE
function(){return new ActiveXObject("Msxml2 .XMLHTTP");} //Some versions of IE
];
for (var i = 0; i < factories.length; i ) {
try {
if (factories[i ]()) {
return factories[i];
}
}
catch (e) {
continue;
}
}
return factory[2 ];
}(),
}


This code seems to have many more steps than the above, but when _ajax._create() is called for the first time, _ajax._create has been changed into an anonymous function compatible with the current browser, and subsequent calls will no longer make judgments;
Statement:
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