JS沙箱模式實例分析
更新時間:2017年09月04日 12:06:28 作者:藍精靈依米
這篇文章主要介紹了JS沙箱模式,結合實例形式分析了JS沙箱模式的原理與實現(xiàn)方法,需要的朋友可以參考下
本文實例講述了JS沙箱模式。分享給大家供大家參考,具體如下:
//SandBox(['module1,module2'],function(box){});
/*
*
*
* @function
* @constructor
* @param [] array 模塊名數(shù)組
* @param callback function 回調函數(shù)
* 功能:新建一塊可用于模塊運行的環(huán)境(沙箱),自己的代碼放在回調函數(shù)里,且不會對其他的個人沙箱造成影響
和js模塊模式配合的天衣無縫
*
* */
function SandBox() {
//私有的變量
var args = Array.prototype.slice.call(arguments),
callback = args.pop(),
//模塊可以作為一個數(shù)組傳遞,或作為單獨的參數(shù)傳遞
modules = (args && typeof args[0] == "string") ? args : args[0];
//確保該函數(shù)作為構造函數(shù)調用
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);
}
//自己的代碼寫在回調函數(shù)里,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數(shù)據(jù)結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數(shù)學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章
js實現(xiàn)四舍五入完全保留兩位小數(shù)的方法
這篇文章主要介紹了js實現(xiàn)四舍五入完全保留兩位小數(shù)的方法,涉及javascript針對浮點數(shù)的數(shù)值運算相關技巧,需要的朋友可以參考下2016-08-08

