Module Mode Small note

Source: Internet
Author: User

When we write a constructor in a normal way (a function called by new), the properties and methods inside it are visible to the outside world.

function Person () {            this. Name = "haha";               This function () {                returnthis. Name;            }

return this; } var New Person (); Console.log (P1.sayname ());//haha Console.log (p1.name);//haha

P1.name = "Ha";
Console.log (P1.sayname ());//ha

The person here defines a name property and a Sayname method that can invoke the corresponding method through the generated object but discovers that the generated object can also call the Name property directly (this is not surprising because name itself is the property of the generated object) Such a pattern does not achieve the purpose of our private property.

To implement a private property, you must pass an anonymous closure

(function () {            //used variables and functions are declared here, scope can only exist in this closure, where the code can still access the external scope, is the problem of the chain of Action        } ());

We declare variables and functions in an anonymous closure, the scope exists only in this closure, the outside world is inaccessible, but the code here can find out the variables through the chain of action

Let's implement a simple example (simple module mode)

varmodule = (function(){            varmy ={}, id= 123; functiongetId () {returnID; The}//private variable and function are declared here, and the outside is inaccessible to my. Id=ID; My.getprivateid=function() {                returngetId (); }            returnmy;//can only access internal private variables and function through the returned my        ()); Console.log (module.        ID); Console.log (Module.getprivateid ());
   

When we have new needs to expand our module (the project team of several people to expand) first he will introduce the previous module file is the above example, and then in the extension (this also implemented the module's multi-person development)

var module = (function(my) {            function() {                return "expands" ;            }             return my;        } (module));        Console.log (Module.say ()); Extends the

The way to do this is to pass the previous module into the anonymous closure function, add its corresponding function, but also to maintain the private variables and functions before, the Var is not necessary here (because the module has been declared before this is a tightly coupled extension mode), This mode requires the order in which the files are loaded

If there is no requirement for the loading order of the files, then the loosely coupled extension pattern can be implemented

var module = (function(my) {            //extension            return  my;        | | {}))

When we pass parameters to an anonymous closure, we pass the module | | {} that is, when the module does not exist, we go to create it this does not require the loading order of our files is required, this is a loosely coupled extension mode, there is a certain limitation, that is, cannot rewrite some properties and methods (because no loading order, when we want to rewrite the time, The corresponding properties and methods may not exist, there is no way to rewrite this statement, that is, the new definition) and here the Var must be written, (because other people would like to read your file will not be able to read)

The tight coupling mode, while limiting the order of loading, gives us the opportunity to override the property method

varmodule = (function(){            varmy = {}; varID = 123; functionA () {returnA;            }; my.b=function(){                return"This is an old func"; }            returnmy;        }()); Console.log (module.b ());//this is old funcvarmodule = (function(my) {varOldfunc =my.b; my.b=function() {                return"This is new Func"; } My.oldfunc=Oldfunc; returnmy;        } (module)); Console.log (module.b ()); This is the new Func Console.log (Module.oldfunc ());//this is the old func

Above is a completed example rewrite the previously defined B method and can access the previous method by re-adding the previous method to the module

Sub-module implementation when we need to implement a submodule under the module above, we can do that.

Module.test = (function() {            var name = "AA",                = {};             function (){
         //console.log (mudule.b ());//Sub-modules can call the parent module's methods they are in a namespace return name; } return my; } ()); Console.log (Module.test.sayName ());//aa

This enables the implementation of a sub-module

In the book of JavaScript design patterns, a way to create a namespace is provided by the way the submodule is created and the parent module has a namespace (sometimes we want to implement a different namespace for the two modules), and the implementation in the book is given below.

First we need a general function that creates a namespace

varMySpace = MySpace | | {}; Myspace.namespace=function(ns_string) {varParts = Ns_string.split ('. ')), Parent=MySpace, I= 0, Length= 0; if(Parts[0] = = = "MySpace") {Parts= Parts.slice (1); }             for(i = 0;length = Parts.length,i < Length;i + = 1) {                if(typeofParent[parts[i]] = = = "undefined") {Parent[parts[i]]= {}; } Parent=Parent[parts[i]]; }            returnparent; }

With the function above, we can create our module in the corresponding namespace.

Myspace.namespace (' MySpace.modules.test ');         = (function() {            var name = "haha",                = {};             function () {                return  name;            }             return my;        } ());
Myspace.namespace (' MYSPACE.MODULES.A ');//create additional module at the same level

Reference JavaScript Design Patterns

Blog http://www.cnblogs.com/TomXu/archive/2011/12/30/2288372.html

Module Mode Small note

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.