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

来源:互联网 发布:泰国的交友软件 编辑:程序博客网 时间:2024/05/22 13:49

继承:

继承通过 ‘.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';    //重写!}
原创粉丝点击