当前位置:Gxlcms > JavaScript > javascript单例模式演示代码javascript面向对象编程_js面向对象

javascript单例模式演示代码javascript面向对象编程_js面向对象

时间:2021-07-01 10:21:17 帮助过:6人阅读

js的单例写法

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

loop.js是一个单例模式的js类:

//一开始就用new 无名类的方式创建。这样就实现了单例的功能。
var loop = new (function(){
// 外部公共函数
// 无限循环的操作
this.setloop = function(fn){Infinite_loop.setLoopFn(fn);} // 参数 1 参数类型 function
this.deleteloop = function(fn){Infinite_loop.deleteLoopFn(fn);} // 参数 1 参数类型 function
this.stoploop = function(){Infinite_loop.stopLoop();}
// 单次循环的操作
this.setloopOne = function(fn){one_loop.setLoopOneFn(fn);} // 参数 1 参数类型 function
this.stoploopOne = function(){one_loop.stopLoopOne();}

// 下面是两个私有的单例模式成员
// 无限循环执行的List对象
var Infinite_loop = new (function(){
this.loop_stop = true;
this.loop_action = new Array();
this.loop_actionID = 0;
var opp = this;
this.setLoopFn = function(fn){
if(typeof(fn)!="function"){
throw new Error("window.loop.setloop's argment is not a function!"); return;
}
for(var i=0;i if(this.loop_action[i] == fn){
throw new Error(fn+" has been registered !");
return;
}
}
this.loop_action.push(fn);
this.startLoop();
};
this.deleteLoopFn = function(fn){
for(var i=0;i if(this.loop_action[i] == fn){
this.loop_action.splice(i,1);
}
}
};

this.Loop = function(){
var run = function(){
if(opp.loop_action.length > 0){
(opp.loop_action[opp.loop_actionID])();
opp.loop_actionID++;
if(opp.loop_actionID>=opp.loop_action.length)opp.loop_actionID=0;
setTimeout(opp.Loop,20);
return;
}
opp.loop_stop = true;
};
run();
}

this.stopLoop = function(){
this.loop_stop = true;
}
this.startLoop = function(){
if(! this.loop_stop)return;
this.loop_stop = false;
this.Loop();
}
})();

/* 单次执行的list对象 */
var one_loop = new (function(){
this.loopOne_stop = true;
this.loopOne_action = new Array();
var opp = this;
this.setLoopOneFn = function(fn){
if(typeof(fn)!="function"){
throw new Error("window.loop.setloopOne's argment is not a function!"); return;
}
this.loopOne_action.push(fn);
this.startLoopOne();
}
this.LoopOne = function(){
function run(){
if(opp.loopOne_action.length>0 && !opp.loopOne_stop){
(opp.loopOne_action.shift())();
setTimeout(opp.LoopOne,20);
return;
}
opp.loopOne_stop = true;
}
run();
}
this.stopLoopOne = function(){
this.loopOne_stop = true;
}
this.startLoopOne = function(){
if(! this.loopOne_stop)return;
this.loopOne_stop = false;
this.LoopOne();
}
})();
})();


下面是实例:loop.html




loop.js







jquery.js
jQuery 是1.2.6版的,小巧的js框架,可以到http://jquery.com/下载
https://img.gxlcms.com/https://img.gxlcms.com/testFile/glass_32x32.gif



其实大家可以再深入思考一下,
例如模拟一个简单工厂类的东西。

var
money = factory.creater ("美元");

人气教程排行