The use of modular programming at work is also a period of time, mainly used in AMD and COMMONJS two styles of modular programming. Modular programming compared to the traditional JS programming style, the traditional JS default is not similar to the Java Class,package Concept, reference to multiple JS prone to pollution global variables, membership coverage and the problem of dependency chaos, in order to avoid such problems, only to derive the modular programming.
Webpack, Nodejs support commonjs style, Commonjs loading module is synchronous, each JS file is a module, has its own scope. The variables, functions, and classes defined in the JS file are private and are not visible to other files.
//Hello.jsModule.exports.hello=function () {Console.log ('Hello world!')}module.exports.sayhello=function (name) {Console.log ('Hello'+name)}//Main.jsvarobj = require ('./hello'); Obj.hello () Obj.sayhello ('Kerry')
The results are as follows:
The COMMONJS specification stipulates that within each module, the module variables represent the current modules. This variable is an object whose exports property (that is, module.exports) is an external interface. Loading a module is actually loading the module's Module.exports property.
The AMD specification is a non-synchronous loading module that allows you to specify a callback function, the AMD specification uses the Define method to define the module, and the browser side generally uses the AMD specification, in conjunction with Requier.js.
// hello.js Define ([],function () { var obj = {}; Obj.hello = function () {Console.log ( "
hello world! " )} Obj.sayhello = function (name) {CONSOLE.L OG ( " hello " + name)} return obj;})
<body><script type="text/javascript" src="require.js" ></script><script type="text/javascript"> require ([ 'hello.js'],function (obj) { Obj.hello (); Obj.sayhello ('Kerry') })</script></body>
The results are as follows:
Commonjs and AMD style of modular programming