JS模块化写法

现代的模块机制,理解它,你也可以写出自己的库,还可以后面动态添加

var MyModules = (function Manager() {
	var modules = {};
	function define(name, deps, impl) {
		for (var i = 0; i < deps.length; i++) {
			console.log(deps,"111")
			deps[i] = modules[deps[i]];
		}
		modules[name] = impl.apply(impl, deps);
	}

	function get(name) {
		console.log(modules)
		return modules[name];
	}
	return {
		define: define,
		get: get
	};
})();

MyModules.define("bar", [], function() {
	console.log(this)
	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(); 

当然ES6提供了更加简洁的写法,那就是
a.js
exexport xxx;
b.js
import hello from “a”;

你可能感兴趣的:(JS模块化写法)