作为一名初学者说说js从零开始面向对象

来源:互联网 发布:认证报名保存数据失败 编辑:程序博客网 时间:2024/05/18 23:55

在谈面向对象的前提的下我们需要来个来个面向过程的函数,便于改写成面向对象。。。
例如来个拖拽函数
window.onload = function(){
var odiv1 = document.getElementById(‘div1’);

        var dx=0;        var dy =0;        odiv1.onmousedown = function (ev){            var ev = ev || event;            var dx = ev.clientX - odiv1.offsetLeft;            var dy = ev.clientY - odiv1.offsetTop;            document.onmousemove = function (ev){                var ev = ev || event;                odiv1.style.left = ev.clientX -dx + 'px';                odiv1.style.top = ev.clientY -dy + 'px'            }            document.onmouseup =function (){                document.onmousemove = null;                document.onmouseup = null;            }        }    }    </script></head><body>    <div id="div1"></div>

这个要是还看不懂,面向对象说了也是白说了。。。。。
接下来 通过一种很通用很简单,但不流行的方法,改写函数
要点:1第一不能有函数嵌套
2.将onload改写成构造函数
3.将全局变量改写成 方法
4.将函数改写成方法
结果然后如下:

var odiv1 = null;
var dx = 0;
var dy = 0;
function drag(id) {
var _this = this;
this.odiv = document.getElementById(id);

this.odiv.onmousedown = function(){    _this.dragdown();};

}

drag.prototype.dragdown =function (ev){
var _this = this;
var ev = ev || event;
this.odiv.dx = ev.clientX - this.odiv.offsetLeft;
this.odiv.dy = ev.clientY-this.odiv.offsetTop;
document.onmousemove = function(){
_this.dragmove();
};
document.onmouseup = function(){
_this.dragup();
};
return false;
}
drag.prototype.dragmove=function dragmove(ev){

        var ev = ev || event;        this.odiv.style.left = ev.clientX -this.odiv.dx + 'px'        this.odiv.style.top = ev.clientY -this.odiv.dy + 'px'    }

drag.prototype.dragup =function dragup(){
document.onmousemove = null;
document.onmouseup = null;
}
在写过程估计就this的指向问题难一点。这个也很好解决,借助调试工具一行行调试,慢慢来,多写几个。掌握这种简单的方法就比较快了

0 0