js面向对象小尝试

知识点:

1、prototype属性

创建实例之前或之后,给构造函数A的prototype对象添加属性,它的所有实例自动会有这个属性。

2、this指针

直接下属函数里 ,this 指向这个对象,否则 都指向window对象

 

制作的小例子如下:

<style type="text/css">
   *{margin:0; padding:0;}
  .txt{ width:200px; height:200px; border:1px solid #000;}
 </style>
 <div class="txt" id="txt">1</div>
    <p class="txt" id="p">2</p>
 <button type="button" onClick="scro1.start()">例1开始</button><button type="button" onClick="scro1.stop()">例1停止</button>
    <button type="button" onClick="scro2.start()">例2开始</button><button type="button" onClick="scro2.stop()">例2停止</button> 
    <script type="text/javascript">
     function scro(txt,obj,t){
     this.txt = txt.split(''); 
     this.obj = obj;
     this.t = t || 1000;
  }
  scro.prototype = {   
    start:function(){
       var selft = this; //注意这里的this指向
       clearInterval(this.timer);       
       this.timer = setInterval(function(){
       //在这个function里的this已经指向的是windows了
        var add =  selft.txt[0];
        selft.txt.shift();
        selft.txt.push(add);
        selft.obj.innerHTML = selft.txt.join('');
      },selft.t);          
    }, 
   stop:function(){
     clearInterval(this.timer);     
    }
  }
  var scro1 = new scro("这是滚动的文字",document.getElementById('txt'));
  var scro2 = new scro("这是另一个滚动的文字",document.getElementById('p'));
    </script>

转载于:https://www.cnblogs.com/clound/archive/2013/03/07/2948510.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值