1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| var foo = (function CoolModule(){ var something = "cool"; var another = [1,2,3]; function doSomething(){ console.log(something); } function doAnother(){ console.log(another.join(",")); } return { doSomething, doAnother } })(); foo.doSomething(); foo.doAnother();
function CoolModule(id) { function identify() { console.log( id ); } return { identify: identify } } var foo1 = CoolModule( "foo 1" ); var foo2 = CoolModule( "foo 2" );
改,包括添加或删除方法和属性,以及修改它们的值。 var foo = (function CoolModule(id){ function change(){ publicAPI.identify = identify2; } function identify1(){ console.log(id); } function identify2(){ console.log(id.toUpperCase()); } var publicAPI = { change, identify:identify1 } return publicAPI; })("foo module") foo.identify(); foo.change(); foo.identify();
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, 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" ) ); foo.awesome();
|