JavaScript Modular Programming

Source: Internet
Author: User

First, the original wording

A module is a set of methods for implementing a specific function.

Simply put the different functions (and the variables that record the state) together, even if it is a module.

function M1 () {//...} function m2 () {//...}

The above functions M1 () and M2 () to form a module. When used, call directly on the line.

The disadvantage of this approach is obvious: "Pollute" the global variable, there is no guarantee that the variable name conflicts with other modules, and the module members do not see a direct relationship.

Ii. the wording of the object

In order to solve the above shortcomings, the module can be written as an object, all the module members are placed in this object.

var module1 = new Object ({_count:0, m1:function () {//...}, M2:function () {//...} });

The above functions M1 () and M2 () are encapsulated in the Module1 object. When used, it is called the property of the object.

However, such a notation exposes all module members, and the internal state can be overridden externally. For example, external code can directly change the value of an internal counter.

Iii. immediate execution of function notation

Using the Execute functions now (immediately-invoked function Expression,iife), you can achieve the purpose of not exposing private members.

var Module1 = (function () {var _count = 0;    var m1 = function () {//...};    var m2 = function () {//...};  return {m1:m1, m2:m2}; })();

Using the notation above, the external code cannot read the internal _count variable.

Console.info (Module1._count); Undefined

Module1 is the basic way of writing JavaScript modules.

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.