作为一名初学者说说js从零开始面向对象
2017-04-08 19:55
337 查看
在谈面向对象的前提的下我们需要来个来个面向过程的函数,便于改写成面向对象。。。
例如来个拖拽函数
window.onload = function(){
var odiv1 = document.getElementById(‘div1’);
这个要是还看不懂,面向对象说了也是白说了。。。。。
接下来 通过一种很通用很简单,但不流行的方法,改写函数
要点:1第一不能有函数嵌套
2.将o
9faa
nload改写成构造函数
3.将全局变量改写成 方法
4.将函数改写成方法
结果然后如下:
var odiv1 = null;
var dx = 0;
var dy = 0;
function drag(id) {
var _this = this;
this.odiv = document.getElementById(id);
}
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){
drag.prototype.dragup =function dragup(){
document.onmousemove = null;
document.onmouseup = null;
}
在写过程估计就this的指向问题难一点。这个也很好解决,借助调试工具一行行调试,慢慢来,多写几个。掌握这种简单的方法就比较快了
例如来个拖拽函数
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.将o
9faa
nload改写成构造函数
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的指向问题难一点。这个也很好解决,借助调试工具一行行调试,慢慢来,多写几个。掌握这种简单的方法就比较快了
相关文章推荐
- 作为一名初学者说说js从零开始面向对象
- 作为一个初学者或者进阶者,这并没有什么错。当一个有能力的程序员而不是领导者,这也没有什么错。真正的错误是,当你知道应该如何去提高时仍然选择做一名初学者。
- 前端这条路怎么走,作为一名后端er,说说我的见解
- java学习作为一名java初学者,如何快速学习java?
- 前端这条路怎么走,作为一名后端er,说说我的见解
- java学习作为一名java初学者,如何快速学习java?
- 详解本地Node.js服务器作为api服务器的解决办法
- js中用$(“#ID”)来作为选择器的问题(id重复的时候)
- js--面向对象--封装
- d3 js 将传进的时间作为时间时间轴
- Js实现简单计算器3 面向对象的方法 优化写法
- js面向对象的五种写法
- 笔记-[面向对象]-JS基于面向对象编程-[1]
- 作为一名资深的JAVA工程师需要了解的知识汇总
- JS模拟面向对象全解(一、类型及传递)
- 从零开始学 Web 之 Vue.js(四)Vue的Ajax请求和跨域
- js笔记--面向对象
- 归纳下js面向对象的几种常见写法
- 关于js面向对象的认识
- 深入理解js面向对象之继承