The module defined by requirejs always returns a singleton object, and mutual interference between modules can be solved by using classes in javascript.
RequireJS defines a module. In general, there are two methods: simple key-value pairs and function dependencies.
1. Simple key-value pairs: a module only contains value pairs without any dependencies.
define({ color: "black", size: 1, method1: function() {}, method2: function() {}});
This writing method is simple, but has great limitations. It only defines the return value of this module and cannot perform some additional initialization work.
The following method is used to define a module, which is more flexible. We can write some code for module initialization in the function body.
define(function () { //Do initial work here return { method1: function() {}, method2: function() {} };});
2. function dependency:
The first parameter is the dependent name array, and the second parameter is the callback function.
After all dependencies of a module are loaded, the callback function is called to define the module.
define(["module1"], function(moudle1) { function calc(){return moudle1.val;}return {"get":calc}; });
The two definition modules are equivalent. requirejs can ensure that A module is loaded only once. Therefore, if both module A and Module B depend on Module C, in fact, both module A and Module B 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, we often want it to be used by multiple modules without mutual interference.
// C Module define ([], function () {// defines a class function DemoClass () {var count = 0; this. say = function () {count ++; return count ;};} return function () {// a new object is returned each time. return new DemoClass ();};}); // A module require (['C'], function (module) {cosole. log (module (). say (); // 1}); // B module require (['C'], function (module) {cosole. log (module (). say (); // 1 });
Every call to Module C is A new object, which can avoid interference and conflict between module A and Module B when using Module C.