沙箱模式解決了命名空間模式的如下幾個缺點:
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 })