JavaScript architecture design 1. Seed Module

Source: Internet
Author: User

1. Seed Module

The seed module is also called the Core module, which is the first part of the framework to execute.

Zongzi module contains functions: Object extension, array, type determination, simple event binding and unloading, no conflict handling, module loading and Domready. This chapter explains the mass framework's seed module as a model.

1.1 Namespaces

Seed module as the first part of a framework, in addition to the overall infrastructure of the building, do you want to give the reader a shocking opening? As the saying goes, a good beginning is half the success.

Now "Overlord" JQuery has a very good opening--iife (immediately called function expression), suddenly attracted readers, let readers eat a reassurance.

Iife is the main infrastructure of the modern JavaScript framework, which wraps itself like a cell membrane to prevent variable contamination. But we have to set a foothold in window, this is the namespace.

1         if(typeof(Ten) = = = "undefined") {2Ten = {};3Ten.function = {}4Ten.array = {}5Ten.class = {}6Ten.jsonp =NewTen.class ()7TEN.XHR =NewTen.class ()8 9}

Looking at the implementation of the major classes of libraries, the first is basically to define a global variable as a namespace, and then extend it, such as Base2 base, ext's ext,jquery jquery, Yui's Yui, Dojo Dojo and so on. In terms of the degree of pollution from global variables, there are two main categories.

Prototype, MooTools and Base2 belong to one category. Prototype's philosophy is to extend the native object of JavaScript.

The second category is jquery, YUI, ext these frameworks. Yui and ext, like the code given above, are structured in a dogpile way. jquery is a way of looking at a selector, so its namespace is a function that makes it easy for users to pass in a CSS expression string, then find it through the selector engine and return a jquery instance. jquery was very weak in the early stages, and it wanted others to use their own framework, but also imagine prototype using the dollar sign as a namespace. Therefore, it deliberately implements a multi-library coexistence mechanism, which switches between $,jquery and the user-specified namespace.

jquery's multi-Library coexistence principle is simple, so it has become a standard for many smaller libraries. First, save the namespace to a temporary variable, notice that this object is not its own frame of things, may be prototype.js and other giants, and then a noconflict put back.

1_jquery = window.jquery, _$ = window.$;//Save the variable with the same name that might exist first.2 3 Jquery.extend ({4Noconflict:function(deep) {5window.$ = _$;//And then put it back .6                     if(deep) {7Window.jquery =_jquery;8                     }9                 returnJQuery;Ten};

But jquery's noconflict is only useful for a single-file class library framework, and you can't copy it if you want ext. So renaming the namespace, ext is null, and then the new JavaScript file is introduced by dynamic loading, and the file is called Ext, which will result in an error.

The mass framework improves the multi-Library coexistence of jquery, which has two namespaces like jquery, a dollar sign, and a long namespace that is dynamically generated based on the URL (jquery is jquery)

            Namespace=doc. Url.replace (/(#.+|\w)/g, ');

The short name of the empty user renaming, the long namespace is loaded with the new module, although the user in the module using the namespace, but when the JavaScript asked to load down, we will be the opposite of the content of the next layer, will be the correct object, the concrete implementation see define method.

1.2 Object Extensions

We need a mechanism to add new functionality to our namespaces. This method is usually called extend or mixin in JavaScript. JavaScript objects are free to add, change, and delete their members before the property descriptor is born, so it is convenient to extend an object. The implementation of a simple extension method is like this.

1             function Extend (destination,source) {2                  for (var in source) 3                     destination[property]=Source[property]4                 return  destination; 5             }

However, the old version of IE has a problem here, it is that a prototype method like object should not be traversed, so the for in loop is unable to traverse the name of the property named ValueOf, ToString. This resulted in the subsequent simulation of the Object.keys method, which was also encountered in the implementation of the problem.

            function (obj) {                var a = [];                  for inch obj);                 return A;            }

Different frameworks, this method different implementations, such as ext is divided into apply and applyif two methods, the former will overwrite the target object with the same name property, and the latter will not. Dojo allows multiple objects to be merged together. jquery also supports deep copy. The following is the mix method of the mass framework, which supports multi-object merging and selection overwrite.

1             functionMix (target, source) {//If the last argument is Boolean, determine if the property with the same name is overwrite2                 varargs =[].slice.call (arguments),3i = 1,4Key, Ride =typeofARGS[ARGS.LENGTH-1] = = "Boolean"? Args.pop ():true;5 6                 if(Args.length = = 1) {//handling of $.mix (hash) Cases7target =! This. Window? This : {};8i = 0;9                 }Ten                  while(Source = arge[i++]) { One                      for(Keyinchsource) { A                         if(Ride | |! (Keyinchtarget)) { -Target[key] =Source[key]; -                         } the                     } -                 } -                 returnTarget; -}

1.3 Array

There are many class array objects under the browser, such as arguments within function, through Document.forms, Form.elements, Document.links,select.options, Document.getelementsbyname, ChildNodes, children, and so on get the collection of nodes (Htmlcollection, NodeList), or custom objects that follow some special wording.

1             var arrarlike={2                 0: "A",3                 1: "1",4                 2: "2",5                 length:36             }

The class array object is a good storage structure, but it is too weak, and in order to enjoy the convenient methods of pure arrays, we will do a conversion before we deal with them.

Generally speaking, as long as [].slice.call can be converted, but the old version of IE Htmlcollection, nodelist is not a subclass of object, using the method as above will cause IE to perform the exception. Let's take a look at how the big libraries deal with it.

JavaScript architecture design 1. Seed Module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.