上一篇说了模块模式,而对于其中的命名空间模式其实也是有着一些问题,比如每添加一个模块或则深入叠加都会导致长命名,并且对于多个库的不同版本同时运行,一不小心就会污染全局标识,而这两天也发现了JSer对此也有解决办法,由于不是特别喜欢这种模式,但是在YUI3中大量的用到了这种模式,顾从网上扒了一篇来说明一下,这种模式就是沙箱模式。
沙箱模式(Sandbox Pattern),顾名思义沙箱模式是创建了一个"沙箱",可以理解为创建了一个黑盒,我们不管在里面做什么都不会影响到外面。而在JavaScript中就意味着,在沙箱中的操作被限死在当前作用域,不会对其他模块和个人沙箱造成任何影响。
废话不多说。我们来看看沙箱模式的具体实现,如下代码所示:
function Sandbox() {var args = Array.prototype.slice.call(arguments),callback = args.pop(),modules = (args[0] && typeof args[0] === "string") ? args : args[0],i;if (!(this instanceof Sandbox)) {return new Sandbox(modules, callback);}this.a = 1;this.b = 2;if (!modules || modules === ‘*‘) {modules = [];for (i in Sandbox.modules) {if (Sandbox.modules.hasOwnProperty(i)) {modules.push(i);}}}for (i = 0; i < modules.length; i++) {Sandbox.modules[modules[i]](this);}callback(this);}Sandbox.prototype = {name: "My Sandbox",version: "1.0",getName: function() {return this.name;}}
当然我们最关心的还是沙箱模式主要应用在哪些场景,下面是沙箱模式几个经典的应用场景:
//使用new操作符new Sandbox(function(box) {console.log(box);})//忽略new操作符的方法Sandbox([‘ajax‘, ‘event‘], function(box) {console.log(box);})//直接传单个参数Sandbox(‘ajax‘, ‘dom‘, function(box) {console.log(box);})//Sandbox的嵌套Sandbox(‘dom‘, ‘event‘, function(box) {//一些代码Sandbox(‘ajax‘, function(box) {//这里的box和外部对象的box并不相同})})
从上面的代码可以发现沙箱模式可以通过将代码包装到回调函数中从而保护全局命名空间,而且他依赖注入的方式也很好的说明了他需要哪些模块,清晰了整个代码的结构。
沙箱模式可以通过对构造函数添加静态属性来扩展模块
Sandbox.modules={};Sandbox.modules.dom=function(box){box.getElement=function(){};box.getStyle=function(){};box.foo="bar";}Sandbox.modules.event=function(box){box.attachEvent=function(){};box.dettachEvent=function(){};}Sandbox.modules.ajax=function(box){box.makeRequest=function(){};box.getRequest=function(){};}
从哪搬得砖
原文:http://www.cnblogs.com/ahjx777/p/3563979.html