Last active
August 18, 2018 04:16
-
-
Save fedorenkodev/61df433fbfc5bbd25a67329e42e78046 to your computer and use it in GitHub Desktop.
Example of module in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var MyModules = (function Manager() { | |
var modules = {}; | |
function define(name, deps, impl) { | |
for (var i=0; i<deps.length; i++) { | |
deps[i] = modules[deps[i]]; | |
} | |
modules[name] = impl.apply( impl, deps ); | |
} | |
function get(name) { | |
return modules[name]; | |
} | |
return { | |
define: define, | |
get: get | |
}; | |
})(); | |
MyModules.define( "bar", [], function(){ | |
function hello(who) { | |
return "Let me introduce: " + who; | |
} | |
return { | |
hello: hello | |
}; | |
} ); | |
MyModules.define( "foo", ["bar"], function(bar){ | |
var hungry = "hippo"; | |
function awesome() { | |
console.log( bar.hello( hungry ).toUpperCase() ); | |
} | |
return { | |
awesome: awesome | |
}; | |
} ); | |
var bar = MyModules.get( "bar" ); | |
var foo = MyModules.get( "foo" ); | |
console.log( | |
bar.hello( "hippo" ) | |
); // Let me introduce: hippo | |
foo.awesome(); // LET ME INTRODUCE: HIPPO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment