javascript面向对象——继承

javascript和其他语言相比,它没有真正意义上的继承,也不能从一个父类extends,要实现它的继承可以通过其他方式来实现:

步骤:1.继承父类的属性 2.继承父类的原型

下面就以一个拖拽为例子:

 1 //Drag.js
 2 function Drag(id){
 3     var _this=this;
 4     this.oDiv=document.getElementById(id);
 5     this.disX=0;
 6     this.disY=0;
 7     
 8     this.oDiv.οnmοusedοwn=function(ev){
 9         _this.fnDown(ev);
10         return false;
11     };
12 }
13 
14 Drag.prototype.fnDown=function(ev){
15     var _this=this;
16     var oEvent=ev||event;
17     this.disX=oEvent.clientX-this.oDiv.offsetLeft;
18     this.disY=oEvent.clientY-this.oDiv.offsetTop;
19     
20     document.οnmοusemοve=function(ev){
21         _this.fnMove(ev);
22     };
23     document.οnmοuseup=function(){
24         _this.fnUp();
25     };
26 };
27 
28 Drag.prototype.fnMove=function(ev){
29     var oEvent=ev||event;
30     this.oDiv.style.left=oEvent.clientX-this.disX+'px';
31     this.oDiv.style.top=oEvent.clientY-this.disY+'px';    
32 };
33 
34 Drag.prototype.fnUp=function(){
35     document.οnmοuseup=null;
36     document.οnmοusemοve=null;
37 };

下面就是子类继承父类,不需要些多余的代码就可以实现拖拽功能:

 1 //LimitDrag.js
 2 function LimitDrag(id){
 3     //1.继承属性    通过call改变当前this指向,实现了给LimitDrag new出来的对象赋值
 4     Drag.call(this, id);
 5 }
 6 
 7 //2.继承原型(object是引用类型)
 8 //若通过直接赋值子类会影响到父类的原型    LimitDrag.prototype=Drag.prototype;    X
 9 for(var i in Drag.prototype){
10     LimitDrag.prototype[i]=Drag.prototype[i];
11 }
12 
13 //这里就实现了子类继承父类,没有写多余的代码就可以拖拽了
14 //===================================================================
15 
16 //这里实现子类自己的方法,也不会影响父类
17 //限制拖拽范围
18 LimitDrag.prototype.fnMove=function (ev)
19 {
20     var oEvent=ev||event;
21     var l=oEvent.clientX-this.disX;
22     var t=oEvent.clientY-this.disY;
23     
24     if(l<0){
25         l=0;
26     }else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth){
27         l=document.documentElement.clientWidth-this.oDiv.offsetWidth;
28     }
29     
30     if(t<0){
31         t=0;
32     }else if(t>document.documentElement.clientHeight-this.oDiv.offsetHeight){
33         t=document.documentElement.clientHeight-this.oDiv.offsetHeight;
34     }
35 
36     this.oDiv.style.left=l+'px';
37     this.oDiv.style.top=t+'px';
38 };

 

转载于:https://www.cnblogs.com/lostyu/p/3653274.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值