Javascript framework to design the reading notes of the seed module

  • 2020-03-30 04:28:13
  • OfStack

1. Namespace :

The namespace in js is extended using the properties of the object. For example, the user defines an object A, under which there are B attributes and C attributes, and both B attributes and C attributes are objects. Therefore, A={B:{},C:{}}, then the user can define the same methods and properties in B object and C object. So B and C belong to different namespaces. We call the methods in B and C objects, and we call them through a.b.ike (), a.c.ike (). Of course A is A property in the window object.

However, in one case, such as the introduction of jquery.js and prototype.js into the boke.jsp page (both of which add the $attribute to the window object), the conflict occurs.

Therefore, there is noConflict() in jquery.js to handle conflicts. Execution flow: the page first introduces prototype, in which case prototype will possess the $attribute of the window. When jquery is introduced, jquery will store the $attribute of the previous window in _$and then use the $attribute itself. At this point, you can call jquery's methods with $. When you now want to use prototype instead of jquery, you can call $.noconflict () and the $will revert to the prototype object. Then you can use the prototype method with $.


  var _$ =  window.$ . _jQuery= window.jQuery ;
  noConflict:function(deep){
           window.$ = _$;
       if(deep)  window.jQuery = _jQuery;
          return jQuery;    //Return values that you can assign to other variable names, such as chaojidan, so that you can call methods in jQuery through chaojidan. < br / >   }

2. Object extension :

The namespace object is there, so we need to extend the functionality. For example, I need to copy all the properties and methods of object A into object B. I don't have to write code in B object one by one.


function mix(target , source){
    var args =  [].slice.call(arguments),i=1,
         isCover = typeof args[args.length-1] =="boolean" ? args.pop():true;  //No, default is true, default is overwrite. < br / >    if(args.length == 1){                                     
  target = !this.window? this:{};
  //If there is only one object argument, extend this object. For example, if I call mix(B) in the context of object A, then this will be A, so the properties and methods of B will be added to object A. But if you call mix(B) in the window, you add properties and methods from the B object to an empty object and return the empty object, in case you overwrite properties and methods with the same name in the window object. (only window objects have window properties)
      i =0;
 }
 while((source = args[i++])){
    for(key in source){
                      if(isCover || !(key in target))   //If the key is overridden, assign it directly. If not, determine whether the key is in the target object. If it is, assign no
         {
          target[key] = source[key];
                      }
           }
   }
   return target;
}

Interviewers in large companies like to ask you about the weight of an array, and you can go and see that each item in an array can be an object, and object A and object B are not equal even though they have the same properties and methods. Strings and Numbers, such as 123 and "123", can be found by searching the Internet.

3. The number of network stations :

Browsers have many kind of array object, the arguments,. The document forms, document. The links, form. The elements, the document. The getElementsByTagName,.childnodes (HTMLCollection, NodeList), etc.

There is also a custom object written in a special way


var arrayLike = {
       0:"a",
       1:"b",
      length:2
}

This object is written as a jQuery object.

We need to convert the above class array object into an array object.

[]. Slice. Call method can solve this problem. However, in the older version of IE,NodeList is not a subclass of Object and cannot use the [].slice.call method.

So we can rewrite a slice method.


A.slice = window.dispatchEvent  ? function(nodes,start,end){   return [].slice.call(nodes . start,end);      }
//If window has dispatchevent& dispatches; The attribute proves to support the [].slice.call method, capability detection. < br / >                  :function(nodes,start,end){
                       var ret = [],n=nodes.length;
        if(end == undefined  ||  typeof end === "number"  && isFinite(end)){   //Ampersand is higher than |, |, so end is not written, or end is a finite number into
                                start = parseInt(start,10)  || 0;   //If start does not exist or is not a number, it is assigned 0.
                                end = end == undefined ? n:parseInt(end,10);    //If end does not exist, it is assigned to n.
            if(start < 0)    start + = n;
            if(end< 0)    end + = n;
            if(end>n)    end  = n;
            for(var i = start;i<end;i++){
                                      ret[i-start] = nodes[i];     //Lower versions of IE use array assignments
                                 }
        }
        return ret;
}

Type judgment :

Js five simple data types are: null, and undefined, number, Boolean, string.

There are also complex data types: Object,Function, RegExp,Date, custom objects such as Person, etc.

Typeof is used for Boolean,number,string, instanceof is used for object type. But they all have flaws. For example, an instanceof an Array in firame is not an instanceof an Array in the parent window, and a call to instanceof returns false. (this question was asked in the 360 draft.) Typeof new Boolean (true)         / / "object"     Wrap object. Boolean,number,string three kinds of wrapper objects, js advanced programming is covered.

There are a lot of people who use typeof document.all to see if it's IE, which is dangerous, because this property is also popular with Google and firefox, so this happens in Google: typeof document.all ;     / / undefined  However, the document. All      //HTMLAllCollection, with typeof, is undefined, but the value of this property can be read.

But now you can use the Object. The prototype. ToString. Call method to judge types. This method can directly output the [[Class]] inside the object. However, IE8 and the following window objects cannot use this method. You can use & cake;   The window = = document  / /   True          The document = = window  / / false          6, 7, 8 times.

NodeType        (1: element &cake;     2: attribute attribute        3: text   Text          9: the document)

How to determine the type in jquery:


  class2type ={}
  jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(i,name){
          class2type [ "[object " + name + "]"  ] = name.toLowerCase();
    //class2type = {"[object Boolean]":boolean,"[object Number ]":number ,"[object String ]":string ,"[object Function ]":function ,"[object     Array ]":array ......}
    });
    jQuery.type = function(obj){             //If obj is null, undefined, etc., it returns the string "null","undefined". If not, it will call the toString method, if it can be called on the judgment, error will return object (IE lower version of the window,Dom and other ActiveXobject objects)
    return obj == null ? String(obj)  : class2type [ toString.call(obj) ]  || "object";
  }

5. DomReady

When js manipulates dom nodes, the page must build a dom tree. Therefore, the window.onload method is usually used. But the onload method does not execute until all resources have been loaded. In order to make the page more responsive to the user's actions, we should use js as soon as the dom tree is built. Instead of waiting for all the resources to be loaded (images,flash).


 if(document.readyState === "complete"){   //In case the js file is not loaded until the Dom document is loaded. Use this judgment to execute the fn method (the method you want to execute). Because when the document is loaded, the value of document.readystate is complete
         setTimeout(fn);      //Asynchronous execution allows the code behind it to execute first. Here is the usage of jQuery, you can not understand. < br / > }
else if(document.addEventListener){//Support DOMContentLoaded event
            document.addEventListener("DOMContentLoaded",fn,false);   //The bubbling < br / >     window.addEventListener("load",fn,false);   //In case the js file is not loaded until the DOM tree is built. The DOMContentLoaded event is not triggered (the trigger has ended), only the load event
is triggered }
else{
  document.attachEvent("onreadystatechange",function(){//For iframe security under IE, sometimes onload is executed first, sometimes not. < br / >     if(document.readyState ==="complete"){
      fn();
    }
  });
  window.attachEvent("onload",fn);   //It always works in case some other listener event is not picked up so that at least the fn method can be triggered by the onload event. < br / >   var top = false;//See if it's
in the iframe      try{//Window.frameelement is an iframe or frame object that contains the page. No is null. < br / >           top = window.frameElement == null && document.documentElement;
      }catch(e){}
     if(top && top.doScroll){  //If there is no iframe, and it is IE
            (function doScrollCheck(){
                     try{
          top.doScroll("left");//Under IE, if the Dom tree is built, you can call the HTML doScroll method
        }catch(e){
                            return setTimeout(doScrollCheck,50);  //If not, continue listening for
                    }
                    fn();
            })
    }
}

The fn method must include the removal of all binding events.

Of course, IE can also use script defer hack, because the script that specifies defer is executed after the DOM tree has been built. But this requires additional js files, which are rarely used in separate libraries.

How to use it: add a script tag to the document and use script.src = "xxx.js" to listen for the script's onreadystatechange event. When this.readystate == "complete", execute the fn method.

That is, after the DOM is built, xxx.js will execute, and its this.readystate will become complete.

Above is the javascript framework design of the first chapter of the reading notes, the content is relatively simple, convenient for everyone to better understand the basic content of this chapter.


Related articles: