JavaScript design mode module (module) pattern _javascript techniques

Source: Internet
Author: User
Tags closure

Modules are an integral part of any powerful application and often help us to clearly isolate and organize the code units in the project.

JS in the implementation of the module method:
1. Object literal notation
2.Module mode
3.AMD Module
4.CommonJS Module
5.ECMAScript Harmony Module

Object literal Amount

Object literals do not need to be instantiated with the new operator, but they cannot be used at the beginning of a statement, since the beginning may be interpreted as the beginning of a block, and the new member can be added to the object literal by using the following assignment statement, Mymodule.property = " Somevalue ".

var mymodule = {
 myproperty: "somevalue",
 myconfig:{
 usecaching:true,
 language: "en"
 },
 // Basic Method
 Mymethod:function () {///
 ...
 },
 ////Output information based on current configuration
 mymethod2:function () {
  Console.log ("Caching is:" + (this.myConfing.useCaching)? Enabled ":" Disabled);
 },

 //overriding current configuration
 mymethod3:function (newconfig) {
 if (typeof newconfig = = " Object ") {
  this.myconfig = newconfig;
  Console.log (this.myConfig.language);
  }
 ,}


;
Mymodule.mymethod3 ({
language: "fr",
usecaching:false
})

Using object literals helps encapsulate and organize your code.

In JavaScript, the module pattern is used to further simulate the concept of a class by allowing a separate object to have public/private methods and variables, thereby masking special parts from the global scope.

Module mode uses closures to encapsulate "private" state and organization. It provides a way to wrap mixed public/private methods and variables to prevent leaks to global scopes and conflicts with other developers ' interfaces. In this mode, only a public API needs to be returned, and everything else is kept in a private closure.
In module mode, declarations of variables and methods are available only within that pattern because of closures, but variables and methods defined on the return object are available to external consumers

The implementation of module mode

var Testmodule = (function () {
 var counter = 0;
 return {
  incrementcounter:function () {return
   ++counter;
  },
  resetcounter:function ()
   { Console.log ("Counter value prior to reset" + counter);
   Counter = 0;}}
) ();

Increase counter
testmodule.incrementcounter ();

Check counter values and reset
testmodule.resetcounter ();

Other parts of the code cannot directly read Incrementcounter () and Resetcounter (). The counter variable is actually completely isolated from the global scope, so it behaves like a private variable whose existence is confined to the module's closure because the only code that can access its scope is the two functions. The above methods have valid namespace settings, so all calls need to be prefixed in the test code.

Module Mode
var mynamspace = (function () {
 //Private counter variable
 var myprivatevar = 0

 ) containing namespace, public, and private variables The private function that records has parameters is
 var myprivatemethod = function (foo) {
  console.log (foo);

 return {
  //public variable
  mupublicvar: "foo",

  //Call public function of private variables and methods
  mypublicfunction:function (bar) {
   myprivatevar++;
   Myprivatemethod (bar);}}
) ();

Referencing global variables
JavaScript has an attribute called an implicit global variable, regardless of whether a variable has been used, the JavaScript interpreter loops through the scope chain to find the Var declaration for the entire variable, and if Var is not found, the interpreter assumes that the variable is a global variable. If the variable is used for assignment operations, if it does not exist before, the interpreter automatically creates it, which means it's easy to use or create a global variable in an anonymous closure, but it's harder to manage the code, especially if the person reading the code looks at a lot of things that distinguish which variables are global and which are local.

However, fortunately in the anonymous function we can provide a relatively simple alternative, we can pass the global variable as a parameter to the anonymous function and then use, compared to the implicit global variable, it is clear and fast, we look at an example:

Global module
var mymodule = (function (jq,_) {

  function privateMethod1 () {
    JQ (". Container"). HTML (test);
  return {
    publicmethod:function () {
      privateMethod1 ()}}}
) (jquery,_);
Mymodule.publicmethod ();

Global module 
var mymodule = (function () {
//Module Object
var module = {};
Privatevariale = "Hello";

function Privatemethod () {
  //...
}
Module.publicproperty = "Foobar";
Module.publicemethod = function () {
} return  
module;

 }) (); 

Declare global variables without having to implement them, and can similarly support concepts that are introduced globally

There are still some deficiencies in module mode:
1. Because of our different ways of accessing public and private members, when we want to change the visibility, we actually have to modify the existence of every member that has ever used it.
2. We cannot access the private members that were later added to the method.
3. You cannot create automated unit tests for private members, which adds additional complexity when a bug needs to fix patches.
4. Developers cannot easily extend private methods

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.