JavaScript Modular Programming

Source: Internet
Author: User

A function can be seen as a behavior or a method, the following two is two methods ———— two modules, but this will pollute the global variables, there is no guarantee that the other modules do not conflict with the variable name, and the module members do not see a direct relationship.

function M1 () {
//...
}

function m2 () {
//...
}

In order to solve the above method, the module can be written as an object, and all the module members are put into this object.

var module1 = new Object ({

_count:0,

M1:function () {
//...
},

M2:function () {
//...
}

});

The call to M1 here is directly module1.m1 (); Yes, but then the code can be rewritten.

If you don't let the code be rewritten here,

var Module1 = (function () {

var _count = 0;

var m1 = function () {
//...
};

var m2 = function () {
//...
};

return {
M1:M1,
M2:m2
};

})();

With the closure of the wording, so that there is no way outside to read the code inside,

Console.info (Module1._count); Undefined

If a module is large and must be divided into several parts, or if one module needs to inherit another module, then it is necessary to use "magnification mode" (augmentation).

var Module1 = (function (mod) {

MOD.M3 = function () {
//...
};

return mod;

}) (Module1);

The code above adds a new method M3 () to the Module1 module and then returns the new Module1 module.

In a browser environment, parts of the module are usually obtained from the web, and sometimes it is not possible to know which part is loaded first. If you use the previous section, the first part of the execution is likely to load a nonexistent empty object, then use the "wide magnification mode".

var Module1 = (function (mod) {

//...

return mod;

}) (Window.module1 | | {});

In this way, the passed in can be an empty object.

JavaScript Modular Programming

Related Article

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.