js面向对象高级

1、json方式面向对象

 var json = {
    a:12,
    b:5,
    c:'abc',
    d:function () {
       alert(this.a);
    }
 }
 json.d();

简单但不适合多个对象

json:适合整个程序里只有一个,写起来比较简单

命名空间:同一类的方法放在一起

2、拖拽和继承

继承:继承父级的属性(相同的代码只需写一遍,只需改变)

// 拖拽来完成
window.onload = function(){
    new Drag('div1');
}
function Drag(id){
    this.oDiv = document.getElementById(id);
    var _this = this;
    this.divX =0;
    this.divY =0;
    this.oDiv.onmousedown=function (ev){
        _this.fnDown(ev);
    }
}
Drag.prototype.fnDown=function (ev){
       var _this = this;
       var oEvent = ev ||event;
        this.divX = oEvent.clientX - this.oDiv.offsetLeft;
        this.divY = oEvent.clientY-this.oDiv.offsetTop;
       document.onmousemove = function(ev){
            _this.fnMove(ev);
       }
       document.onmouseup = function(){
            _this.fnUp(ev);
       }
        
}
Drag.prototype.fnMove =function(ev){
        var boxEvent = ev || event;
        var boxX = boxEvent.clientX-this.divX;
        var boxY = boxEvent.clientY-this.divY;
        this.oDiv.style.left = boxX+'px';
        this.oDiv.style.top = boxY+'px';
    
}
Drag.prototype.fnUp =function(){
        document.onmousemove=null;
        document.onmouseup = null;
    
}

把上面的代码写个对应他的继承的代码如下:

function limitDrag(id){
  Drag.call(this,id);
}
for(var i in Drag.prototype){
  limitDrag.prototype[i] =Drag.prototype[i];
}
//这样就继承了drag那个js里面的属性

 

如果想在继承后的代码里面另外的加新的限制的话可以对应的调整如下:

function limitDrag(id){
  Drag.call(this,id);
}
for(var i in Drag.prototype){
  limitDrag.prototype[i] =Drag.prototype[i];
}
//然后对于继承后的属性在进行进一步的调整 limitDrag.prototype.fnMove
= function(ev){ var boxEvent = ev || event; var l = boxEvent.clientX-this.divX; var r = boxEvent.clientY-this.divY; if(l <0){ l =0; }else if(l >document.documentElement.clientWidth -this.oDiv.offsetWidth){ l =document.documentElement.clientWidth -this.oDiv.offsetWidth; } if(r<0){ r=0; }else if(r>document.documentElement.clientHeight -this.oDiv.offsetHeight){ r = document.documentElement.clientHeight -this.oDiv.offsetHeight; } this.oDiv.style.left = l+'px'; this.oDiv.style.top = r+'px'; }

 3、本地对象(非静态对象),内置对象(静态对象),宿主对象:Js的运行环境(一般来说例如:DOM,BOM);

posted @ 2015-06-24 17:04  前行者在此  阅读(60)  评论(0)    收藏  举报