There are 2 ways to define a module in Requirejs: Simple key-value pairs and functional dependencies.
1. simple Key-value pairs : A module contains only value pairs, no dependencies
Define ({ color: "Black", size:1, method1:function () {}, method2:function () {}});
This kind of writing is simple, but there are a lot of limitations, just define the module's return value, do not do some additional initialization work.
It is more flexible to define modules in the following way, and we can write some module-initialized code in the function body.
Define (function () { //do initial work here return { method1:function () {}, method2:function () {} };});
2. function-dependent :
The first parameter is an array of dependent names, and the second is a callback function.
After all dependencies on the module have been loaded, the callback function is invoked to define the module.
Define (["Module1"], function (moudle1) { function calc () {return moudle1.val;} return {"Get": Calc}; });
These 2 ways of defining modules are equivalent, Requirejs can guarantee that a module will only be loaded once, so if both A and B modules are dependent on the C module, then both A and B modules use the same object.
C module define ([],function () {var count = 0;function Saycount () {Count++;return count;} return {"Say": Saycount};}); A module require ([' C '], function (module) { cosole.log (Module.say ());//1});//b module require ([' C '], function ( Module) {Cosole.log (Module.say ());//2});
If we define a module, many times we want it to be used by multiple modules without interfering with each other.
C module define ([],function () { //] defines a class function DemoClass () {var count = 0;this.say = function () {Count++;return count;}; } return function () {//Returns a new object each time return DemoClass ();};}); A module require ([' C '], function (module) { cosole.log (module (). Say ());//1});//b module require ([' C '], function (module) {Cosole.log (module (). Say ());//1});
Each call to module C, the return is a new object, in this way can avoid the A and B modules in the use of module C interference and conflict.
The modules defined by REQUIREJS are always returned as singleton objects, and can be used to solve the problem of mutual interference between modules by using the classes in JavaScript