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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2020-05-12 我要评论
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<this.loop_action.length;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<this.loop_action.length;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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>loop.js</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="loop.js"></script>
<script type="text/javascript">

function moveLayer1(){
    this.moveleft = true;
    this.movedown = true;
    this.x1 = 100
    this.y1 = 100;
    this.x2 = 800;
    this.y2 = 400;

}

moveLayer1.prototype.move = function(){
        var divLayer1 = document.getElementById("Layer1");

        var l = parseInt(divLayer1.style.left),
            t = parseInt(divLayer1.style.top);
            var r = parseInt(Math.random()*20);
        if(l < this.x2 && this.moveleft){
            l+=1+r;
            if(l>this.x2-1)this.moveleft = false;
        }else if(l > this.x1 && ! this.moveleft){
            l-=1+r;
            if(l < this.x1+1)this.moveleft = true;
        }

        if(t < this.y2 && this.movedown){
            t+=1+r;
            if(t>this.y2-1)this.movedown = false;
        }else if(t > this.y1 && ! this.movedown){
            t-=1+r;
            if(t < this.y1+1)this.movedown = true;
        }

        divLayer1.style.left =l+"px";
        divLayer1.style.top = t+"px";
}


function circle(){
    this.r = 50;
    this.rx = 500;
    this.ry = 500;
    this.x;
    this.y;
    this.angle = 0;
    this.speedAngle = 10;

}

circle.prototype.init = function(){
    this.setXY();
    $("body").append('<div id="cd" class="Layer2" style="left:'+this.x+'px;top:'+this.y+'px;"><img src="testFile/glass_32x32.gif" /></div>');
    $("body").append('<div class="Layer1" style="left:'+this.rx+'px;top:'+this.ry+'px;"></div>');
}

circle.prototype.setXY = function(){
    this.x = this.rx + this.r*Math.cos(this.angle/(180/Math.PI));
    this.y = this.ry + this.r*Math.sin(this.angle/(180/Math.PI));
}

circle.prototype.draw = function(){
    this.angle +=this.speedAngle;
    this.setXY();
    var f = document.getElementById("cd");
    //$("body").append($("#cd").clone());
    f.style.left =this.x+"px";
    f.style.top = this.y+"px";
}




function timetable(){
var f = document.getElementById("daa");
var d = new Date();
f.innerHTML = "现在时间:"+d.getUTCFullYear()+"年"+d.getUTCMonth()+"月"+d.getUTCDate()+"日 星期"+d.getUTCDay()+" "+d.getUTCHours()+":"+d.getUTCMinutes()+":"+d.getUTCSeconds();
}

var lenstr = -1;
function prints(){
    var str = document.getElementById("sourse").innerHTML;
    if(lenstr<str.length){
        lenstr++;
        var f = document.getElementById("prin");
        //if(lenstr%100==0)f.innerHTML +="<br />";
        f.innerHTML += str.charAt(lenstr);
    }else{
        loop.deleteloop(prints);
    }
}

var movediv = new moveLayer1();
function imgMove(){movediv.move();}

var mycircle = new circle();
function drawCircle(){mycircle.draw();}


function winInit(){
mycircle.init();
loop.setloop(drawCircle);
loop.setloop(imgMove);
loop.setloop(timetable);
loop.setloop(prints);
}

</script>
<style type="text/css">
<!--
.Layer1 {
    position:absolute;
    overflow:hidden;
    color:#fff;
    width:50px;
    height:50px;
    z-index:50;
}
.Layer2 {
    position:absolute;
    overflow:hidden;
    color:#fff;
    width:40px;
    height:40px;
    z-index:1;
}
-->
</style>
</head>

<body onload="winInit();">

<div id="daa"></div>
<div id="Layer1" class="Layer1" style="left:190px; top:101px;">
<img src="testFile/glass_32x32.gif" name="mimg" width="40" height="40" id="mimg" /></div>
<pre id="prin"></pre>


<div id="sourse" style="display:none">

        var x = 1;
        var y = 2;
        var z = 3;

        var sum;

        function Plus(a, b)
        {
                var z = 0;
                var i = 0;
                for (i = 0; i < arguments.length; i++)
                {
                           z += arguments[i];
                }
                setTimeout( function() {alert(z);}, 6000); //可以带变量参数的setTimeout调用形式
                return z;
        }

        setTimeout( function(){ sum = Plus(x, y, z); }, 3000);
         /*除了可以带变量参数还可以获取返回值的setTimeout调用形式*/
</div>
</body>
</html>

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



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

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们