Share 9 programming tips for javascript that I think are important

  • 2020-06-01 08:20:19
  • OfStack

1. Use your judgment wisely:

In js, NaN,undefined,Null,0,"" is false when converted to bool, so you can write it like this.


if(!obj)  {}

Represents what an object does if it is false, because if obj is any of the above, then it is false,! false is true, so you don't need if(obj==null || obj == NaN...) .

2. Smart operators:

Here's a classic trick: get a timestamp.


var dataspan = new Date()*1;

As we know, js is a weakly typed language, and Date() returns a string representing the time with which arithmetic operations are performed to get the conversion, which is the timestamp of the result.

3. Use regular expressions wisely:


/.a/ig.exec('xsas')
// It's like creating 1 a reg Object, called exec Method, of course, can also call other methods, such as: test(),match() And so on.

4. Take the maximum and minimum values of the array:


var values = [1,2,3,40,23];
var max = Math.Max.apply(Math,values);

Call Max.apply, set the object to Math, and pass one Values to determine the maximum.

5. Memory optimization:


function p(){this.p='moersing'}; var p1 = new p(); 
   p1.xx
   p1.xx
   .......
   p1=null;  // After the operation is completed, the pair is finally manually unbuttoned p1 The reference.

6. Most popular way to create objects (prototype mode) :


function c(){
    this.name ='moersing';
    this.age=18;
    this.books=['javascript develop','C# develop'];
  }
  c.prototype={
       displayBookName:function (){
        foreach(var t in this.books)
        {
           document.write(this.books[t]);
        }
    }
}

The biggest drawback of the stereotype construction pattern is the sharing of reference types, so you define reference types in constructors and generic methods in stereotypes, using this references.

7. Block-level scopes and private variables

In javascript, there are no block-level scopes or private variables, but these effects can be simulated with some features.

7.1 block-level scope:


(function(){
      // Block-level scopes
}
)();

An anonymous function is surrounded by a parenthesis, which I call "function normalization". In other words, it can be called like a standard function, such as:


 var name =function(){};
(name)();//1 You wouldn't write it like that ;

Benefits to do so is, on the outside of the () cannot access to the variables in the function, also became a block-level scope, as used in this way 1 write plug-ins, global (global) will no longer add additional variables, and, after the function has been completed, the internal variables defined has been destroyed, so there will be no closure features existing problems.

7.2 private variables:


function private()
 {
   var name = 'moersing';
   this.getName = function(){
   return this.name;
   }
}

Private variables are essentially limited by the scope of the function (which is not externally accessible), and then you define a method that returns the corresponding variable, and that's it.

8. DOM NodeList:

nodeList is a dynamic element, which means that if any element is added to the document, nodeList will be updated in real time, such as:


var alldiv = document.getElementsByTagName('div');
    for(var i=0;i<alldiv.length;i++)
    {
        var div = document.createElement('div');
        div.innerHTML= i.toString();
        document.body.appendChild(div);
    }

This code creates an infinite loop in which one div is created, and then the appendChild method adds it to body, and all alldiv are updated immediately, so i < alldiv.length will never work. To solve this problem, you can:


var alldiv = document.getElementsByTagName('div');
    var len,i;
    for(i=0,len=alldiv.length;i<len;i++)
    {
        var div = document.createElement('div');
        div.innerHTML= i.toString();
        document.body.appendChild(div);
    }

It is recommended that you do not perform frequent NodeList operations, as each operation will perform a query of the DOM tree once.

In addition to the methods described above, API(selector API Level1) newly added to HTML5 can also solve this problem. It is similar to linq of C# in a timely manner. As for what linq is in a timely manner, I will update blog in the future.


var allDiv= document.querySelectorAll('div');
    for(var i=0;i<alldiv.length;i++)
    {
        var div = document.createElement('div');
        div.innerHTML= i.toString();
        document.body.appendChild(div);
    }

querySelectorAll requires 1 parameter, 1 CSS selector, similar to $() in jquery, which returns NodeList as a timely, non-dynamic DOM collection.

In addition, there is an querySelector, which returns the first matched element. See HTML5 API for details

http://www.w3.org/standards/techs/dom#w3c_all

or

https://developer.mozilla.org/zh-CN/docs/Web/API

In addition, I am also preparing a paper on blog, specifically about HTML5 API, please pay attention to it.

9. DOM performance:

Don't do such a stupid thing (I did...)


for(var i=0;i<10;i++)
    {
       document.querySelector('ul').innerHTML="<li>"+i+"</li>";
    }

Assigning an innerHTML value to an object calls the built-in C++ parser to parse the string, which is fast, but it is best not to do so, as there is a certain performance penalty.

It's best to do this:


var ih=null; for(var i=0;i<10;i++)
 {
    ih+="<li>"+i+"</li>";
 }
  document.querySelector('ul').innerHTML=ih;

Some other performance optimization topics will be updated when there is time.

That's all for this article, I hope you enjoy it.


Related articles: