原型的继承和拖拽继承实例

继承:

继承通过 ‘.call( )’方法进行,可以通过不同的参数来改变this的值:

function show(a,b)
        {
            alert('this是:'+this+'\na是:'+a+'\nb是'+b);
        };
        show(12,5);
        show.call('abc',12,5);//this的值可以改变

现在通过一个实例来展现是如何继承的。
首先将之前的一个案例——完美拖拽,用其JS部分构建一个js脚本:

function Drag(id)
{
    var that=this;
    this.disX=0;
    this.disY=0;

    this.oDiv=document.getElementById(id);//记得要把div1换成id ,不能出现单一变量!!!
    this.oDiv.onmousedown=function(ev)
    {
        that.fnDown(ev);//一定要记得this要换掉!!

        return false;//防止选中
    };
}
Drag.prototype.fnDown = function(ev)
{
    var that=this;//将this指向的对象保存下来。
    var oEvent=ev||event;
    this.disX=oEvent.clientX-this.oDiv.offsetLeft;
    this.disY=oEvent.clientY-this.oDiv.offsetTop;
    document.onmousemove=function(ev)//用函数模式防止事件被赋值
    {
        that.fnMove(ev);
    };
    document.onmouseup=function()
    {
        that.fnUp();
    };
};

Drag.prototype.fnMove = function (ev) 
{
    var oEvent=ev||event;
    this.oDiv.style.left=oEvent.clientX-this.disX+'px';
    this.oDiv.style.top=oEvent.clientY-this.disY+'px';
};

Drag.prototype.fnUp = function ()
{
    document.onmousemove=null;
    document.onmouseup=null;
};

属性的继承通过call()方法,而原型的继承通过循环遍历赋值进行:

下列为继承drag.js的脚本limitdrag.js:

function LimitDrag(id)
{
    Drag.call(this,id)// 继承属性的方式    
};

for(var i in Drag.prototype)
{
    LimitDrag.prototype[i]=Drag.prototype[i];
    //利用循环继承方法,从而在操作时不会影响Drag
}
LimitDrag.prototype.fnMove = function (ev) 
{
    var oEvent=ev||event;
    var l=oEvent.clientX-this.disX;//先把值存起来
    var t=oEvent.clientY-this.disY;

    if (l<0) {
        l=0;
    }else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth){
        l=document.documentElement.clientWidth-this.oDiv.offsetWidth;
    }//顺序很重要,要在前面。

    this.oDiv.style.left=l+'px';
    this.oDiv.style.top=t+'px';
    //重写!
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值