javascript沙箱模式

沙箱模式解决了命名空间模式的如下几个缺点:

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
})

 

  

 

转载于:https://www.cnblogs.com/fengzekun/p/3893912.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值