源码网,源码论坛,源码之家,商业源码,游戏源码下载,discuz插件,棋牌源码下载,精品源码论坛

 找回密码
 立即注册
楼主: ttx9n

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

[复制链接]

7万

主题

861

回帖

32万

积分

论坛元老

Rank: 8Rank: 8

积分
329525
发表于 2010-4-9 10:40:54 | 显示全部楼层 |阅读模式
单例模式的好处就是:类只实例化一次,省资源,节省开销,提高速度,学习js面向对象编程的朋友可以参考下。 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 == 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 == 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;
                }
                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 ("美元");
回复

使用道具 举报

0

主题

2万

回帖

0

积分

中级会员

Rank: 3Rank: 3

积分
0
发表于 2022-11-1 06:57:28 | 显示全部楼层
天天源码社区。。。。
回复 支持 反对

使用道具 举报

16

主题

2万

回帖

174

积分

注册会员

Rank: 2

积分
174
发表于 2022-12-16 14:42:18 | 显示全部楼层
的沙发水电费水电费
回复 支持 反对

使用道具 举报

2

主题

2万

回帖

69

积分

注册会员

Rank: 2

积分
69
发表于 2023-6-28 00:21:51 | 显示全部楼层
源码源码源码源码源码源码源码源码源码源码源码源码源码
回复 支持 反对

使用道具 举报

0

主题

2万

回帖

87

积分

注册会员

Rank: 2

积分
87
发表于 2023-11-9 21:03:18 | 显示全部楼层
加快速度很快就撒谎
回复 支持 反对

使用道具 举报

0

主题

1万

回帖

68

积分

注册会员

Rank: 2

积分
68
发表于 2024-3-4 22:58:24 | 显示全部楼层
下载来瞧瞧
回复 支持 反对

使用道具 举报

1

主题

2万

回帖

155

积分

注册会员

Rank: 2

积分
155
发表于 2024-7-14 13:10:17 | 显示全部楼层
不错的源码论坛
回复 支持 反对

使用道具 举报

2

主题

2万

回帖

99

积分

注册会员

Rank: 2

积分
99
发表于 2024-7-28 08:44:09 | 显示全部楼层
飞飞飞飞飞飞飞飞飞飞飞飞飞
回复 支持 反对

使用道具 举报

16

主题

2万

回帖

174

积分

注册会员

Rank: 2

积分
174
发表于 2024-8-27 17:14:31 | 显示全部楼层
借款金额看了就立刻
回复 支持 反对

使用道具 举报

0

主题

2万

回帖

55

积分

注册会员

Rank: 2

积分
55
发表于 2024-9-3 05:21:26 | 显示全部楼层
激动人心,无法言表!
回复 支持 反对

使用道具 举报

高级模式
B Color Image Link Quote Code Smilies

本版积分规则

手机版|小黑屋|网站地图|源码论坛 ( 海外版 )

GMT+8, 2025-2-9 13:03 , Processed in 0.071382 second(s), 22 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表