Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var require = (function(moduleMode)
- {
- var _cache = {},
- _ajax = new XMLHttpRequest();
- return function require(file)
- {
- if(!_cache[file])
- {
- try
- {
- // async is set to false to make sure the browser waits for the content to be included.
- _ajax.open('GET', file, false);
- _ajax.send();
- if(moduleMode)
- {
- // Make sure 'this' inside the module points towards a fresh object, not the window.
- _cache[file] = new Function(_ajax.responseText).call({});
- }
- else
- {
- // Make sure that the scope of the file is the window, not this place here.
- eval.call(window, _ajax.responseText);
- _cache[file] = true;
- }
- }
- catch(e)
- {
- // Intercept any error to give a slighly more usefull message;
- throw(e.message + ' in file ' + file);
- }
- }
- return _cache[file];
- }
- })(true);
- var bar1 = require('js/bar.js');
- var bar2 = require('js/bar.js');
- var bar3 = require('js/bar.js'); // Thanks to caching, all 3 of these are references to the same object.
- console.log(bar1.something);
- bar1.something = 'thing';
- console.log(bar2.something); // The module itself is a single instance, so values are shared.
- var b1 = new bar1.Bar(); // New instances of objects inside the module
- var b2 = new bar2.Bar();
- b1.x(); // Prototypes work accross modules
- b2.x(); // Prototypes are still shared
- //----- js/bar.js -----//
- var foo = require('js/foo.js'); // Will include js/foo.js if it is not in the cache already.
- var something = 'some';
- function Bar()
- {
- console.log(foo.param);
- }
- // Why not put a module as prototype?
- Bar.prototype = foo;
- // Carefully select what is publicly available.
- return {
- Bar:Bar,
- something:something
- }
- //----- js/foo.js -----//
- console.log('Imported!'); // Only fires once, thanks to caching.
- // Private var, can not be accessed outside this module.
- var i = 1;
- // 'this' refers to a new object {}, so it's save to use.
- this.x = function(){ console.log(i ++); };
- this.param = 'value';
- // Make this the module
- return this;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement