Module mode closures self-contained modules var Testmodule = (function () {var counter = 0; return {incrementcounter:function () {return ++counter; }, Resetcounter:function () {Console.log ("counter value prior to reset:" + counter); Counter = 0; } };}) (); Testmodule.incrementcounter (); Testmodule.incrementcounter (); Testmodule.resetcounter ();//contains namespaces, Module mode var MyNamespace = (function () {var myprivatevar = 0) for shared and private variables; var myprivatemehod = function (foo) {console.log (foo); }; return {mypublicvar: "foo", Mypublicfunction:function (bar) {myprivatevar++; Myprivatemehod (bar); }}) (); Mynamespace.mypublicfunction (' Hello world! '); /using modular thinking to realize the shopping cart var Basketmodule = (function () {///private var basket = []; function Dosomethingprivate () {console.log ("dosomethingprivate run"); } function Dosomethingelseprivate () {console.log ("dosomethingelseprivate run"); }//Returns the shared object of the exposure return {additem:function (values) {Basket.push (values); }, Getitemcount:function () {return basket.length; }, Dosomething:dosomethingprivate, Gettotal:function () {var itemCount = This.getitemcount (); Total = 0; while (itemcount--) {total+= basket[itemcount].price; } return total; },}) (); Basketmodule.additem ({item: "Bread", price:0.5}); Basketmodule.additem ({item: "DSS", price:0.5} ); Console.log (Basketmodule.getitemcount ()); Console.log (Basketmodule.gettotal ());
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Javascrip Modular Mode notation