var something = "cool";
var another = [1,2,3];
function doSomething(){
console.log( something );
}
function doAnother(){
console.log( another.join("!") );
}
return {
doSomething: doSomething,
doAnother: doAnother
};
}
var foo = Module();
foo.doSomething();
foo.doAnother();
这个模式在javascript中被称为模块。
首先,Module()只是一个函数,通过调用它来创建一个模块实例。
其次,Module()方法返回一个用对象字面量语法来表示的对象。这个对象中包含对内部函数而不是内部数据变量的引用,从而来确保内部数据变量的私有化。可以将这个返回的对象看作是模块的公共API。
注:doSomething()和doAnother()函数具有涵盖模块实例内部作用域的闭包。
模块模式需要具备两个必要的条件:
1. 必须有外部的封闭函数,该函数必须至少被调用一次(每次调用都会创建一个新的模块实例)
2. 封闭函数必须返回至少一个内部函数,这样内部函数才能在私有作用域中形成闭包,并且可以访问或者修改私 有的状态。
当然,我们也可以通过一个简单的改进来实现单例模式:
var foo = (function Module(){
var something = "cool";
var another = [1,2,3];
function doSomething(){
console.log( something );
}
function doAnother(){
console.log( another.join("!") );
}
return {
doSomething: doSomething,
doAnother: doAnother
};
})();
foo.doSomething();
foo.doAnother();
现代的模块机制(AMD):
var MyModule = (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[naem];
}
return {
define: define,
get: get
};
})();
怎么使用呢?
MyModule.define("bar", [], function(){
function hello(who){
return "my name is" + who;
}
return {
hello: hello
}
});
MyModule.define("foo", ["bar"], function(bar){
var hungry = "jianlu";
function awesome(){
console.log( bar.hello( hungry ).toUpperCase() );
}
return {
awesome: awesome
}
});
var bar = MyModule.get("bar");
var foo = MyModule.get("foo");
console.log( bar.hello("jianlu") );
foo.awesome();
未来的模块机制
在ES6中,一个文件就是一个模块:
bar.js
function hello(who){
return "my name is" + who;
}
export hello;
foo.js
//仅从“bar”模块导入hello
import hello from "bar";
var hungry = "jianlu";
function awesome(){
console.log( hello( hungry ).toUpperCase() );
}
export awesome;
baz.js
module foo form "foo";
module bar form "bar";
console.log( bar.hello("jianlu") );
foo.awesome();
注: import可以将一个模块中的一个或多个API导入到当前的作用域中,并分别绑定在一个变量上。
module会将整个模块的API导入到并绑定到一个变量上。