沙箱模式解决了命名空间模式的如下几个缺点:
1.对单个全局变量的依赖变成了应用程序的全局变量依赖。在命名空间模式中,是没有办法使同一个应用程序或库的2个版本运行在同一个页面中。
2.对这种以点分割的名字来说,需要输入更长的字符,并且在运行时需要解析更长的时间,比如MYAPP.utilities.array
顾名思义,沙箱模式提供了一个可用于模块运行的环境,且不会对其他模块和个人沙箱造成任何影响。
Sanbox.modules = {}; Sanbox.modules.array = function(box){
var array_string = '[object Array]',
opt = Object.prototype.toString;
box.isArray = function(a){
return opt.call(a) === array_string;
}
}
Sanbox.modules.object = function(box){
var obj_string = '[object Object]',
opt = Object.prototype.toString;
box.isObject = function(a){
return opt.call(a) === obj_string;
}
}
function Sanbox(){
var args = Array.prototype.slice.call(arguments),
callback = args.pop(),
//如果是字符串取arguments,否则取第一个参数数组
modules = (args[0] && typeof args[0] === 'string') ? args : args[0],
i;
//强制使用new
if( !(this instanceof Sanbox) ){
return new Sanbox(modules,callback);
}
//如果没有传入参数,存储所有模块
if( !modules || modules === '*'){
modules = [];
for( i in Sanbox.modules){
if( Sanbox.modules.hasOwnProperty(i) ){
modules.push(i);
}
}
} for( i=0; i<modules.length; i++){
//调用每个模块方法
Sanbox.modules[modules[i]](this);
}
//回调调用
callback(this); }
Sanbox(['array','object'],function(box){
var arr = [1,2,3,4];
var obj = { x : 1,y:2};
console.log( box.isObject(obj) ); //输出:true
console.log( box.isArray(arr) ); //输出:true
})