本文實例講述了JS沙箱模式。分享給大家供大家參考,具體如下:
//SandBox(['module1,module2'],function(box){});/**** @function* @constructor* @param [] array 模塊名數組* @param callback function 回調函數* 功能:新建一塊可用于模塊運行的環境(沙箱),自己的代碼放在回調函數里,且不會對其他的個人沙箱造成影響和js模塊模式配合的天衣無縫** */function SandBox() { //私有的變量 var args = Array.prototype.slice.call(arguments), callback = args.pop(), //模塊可以作為一個數組傳遞,或作為單獨的參數傳遞 modules = (args && typeof args[0] == "string") ? args : args[0]; //確保該函數作為構造函數調用 if (!(this instanceof SandBox)) { return new SandBox(modules,callback); } //不指定模塊名和“*”都表示“使用所有模塊” if (!modules || modules[0] === "*") { for(value in SandBox.modules){ modules.push(value); } } //初始化所需要的模塊(將想要的模塊方法添加到box對象上) for (var i = 0; i < modules.length; i++) { SandBox.modules[modules[i]](this); } //自己的代碼寫在回調函數里,this就是擁有指定模塊功能的box對象 callback(this);} SandBox.prototype={ name:"My Application", version:"1.0", getName:function() { return this.name; } };/** 預定義的模塊** */SandBox.modules={};SandBox.modules.event=function(box){ //私有屬性 var xx="xxx"; //公共方法 box.attachEvent=function(){ console.log("modules:event------API:attachEvent") }; box.dettachEvent=function(){ };}SandBox.modules.ajax=function(box) { var xx = "xxx"; box.makeRequest = function () { }; box.getResponse = function () { };}SandBox(['event','ajax'],function(box){ box.attachEvent();})運行效果截圖:


更多關于JavaScript相關內容可查看本站專題:《javascript面向對象入門教程》、《JavaScript中json操作技巧總結》、《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答