Modules are an integral part of any powerful application architecture, and it often helps us to clearly separate and organize the code units in the project.
JavaScript implements several methods of module mode:
(1) Object literal notation
(2) Module mode
(3) AMD mode
(4) COMMONJS module
(5) ECMAScript Harmony
1. Object literals
Example:
var mymodule={ myproperty: "somevalue", myconfig:{ usecaching:true, language: "en" }, Mymethod:function () { console.log ("Hello World"); } } Module.mymethod ();
Use object literals to help encapsulate and organize your code.
2.Module mode
The module schema was originally defined as a way to provide private and common encapsulation of classes in traditional software engineering.
In JavaScript, the module pattern is used to further simulate the concept of a class, which enables a single object to have public/private methods and variables, masking special parts from the global scope and avoiding naming conflicts.
Example: Shopping Cart
var basketmodule= (function () { var basket=[]; function Dosomethingprivate () { //... } Return { additem:function (values) { Basket.push (values); }, getitemcount:function () { return basket.length; }, gettotal:function () { var itemcount=this.getitemconunt (), total=0; while (itemcount--) { total+=basket[itemcount].price; return total;}}} ) ();
Advantages:
(1) Only our modules can enjoy the freedom to have private functions. Because they are not exposed to the rest of the page.
(2) Since functions are often declared and named, this makes it easy to display the stack in the debugger when trying to find which functions throw an exception.
3. Improvement--Revelation mode (revealing Module)
Cause: Heilmann for this situation, when he wants to invoke a public method from another method or access a public variable, the name of the main object must be repeated. He doesn't like it either. When using module mode, you must switch to object literal notation to make a method public.
He creates a new pattern that simply defines all of the functions and variables within the private scope and returns an anonymous object that has a pointer to a private function that he wants to show as public.
Example:
var revealingmodule= (function () { var privatevar= "Private", publcvar= "Hello World"; function Privatefunction () { console.log ("Name:" +privatevar); } function Publicsetname (strName) { privatename=strname; } function Publicgetname () { privatefunction (); } return { setname:publicsetname, greeting:publicvar, getname:publicgetname } });
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
module modules for JavaScript design patterns