Javacript design mode-----Module mode

Source: Internet
Author: User
Tags closure

In some large projects are often used to the module, here, we will understand what is the module mode. The simplest method of module mode will be used by everyone, as shown below:

var a = {     b:1,     c:2  }

The direct amount of such an object can already represent the definition of a module. But here's the problem: the B and C properties inside a object are public, which means we can arbitrarily change the value outside. The modular design requires that we try our best to implement the values and methods in the module without being externally altered to form an independent or private environment. So we can write this:

var count = (function (window, undefined) {var total = 0;//Private member variable var c =  function (q) {//private method, Closure function total++;} return {count:c//exposed private method,};}) (window, undefined)

As you can see, Count finally accepts a self-polygon amount returned by the anonymous function, where the Count method is also the private C's public method alias is the closure function that contains the context within the anonymous function, through which we can change the value of total to achieve total privatization. We can change the value of total in this way.

Count.count ();//So the total value is incremented by 1

In the example above we can see some features of the module pattern:

  1. Modular, REUSABLE
  2. Encapsulates variables and function, and the global namaspace does not touch, loosely coupled
  3. Only exposes methods that are available to public, and all other private methods are hidden.

Modular design is often referenced in large applications. With some module loaders, and AMD specifications, we can organize projects in order to achieve maintainable, high-efficiency code.

Javacript design mode-----Module mode

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.