打地鼠,普通和面向对象写法
面向对象特别适合复杂的开发,对于简单的,不太推荐使用面向对象。
这里只是举一个小例子解释什么是面向对象。
目录
普通写法
- 样式以及布局:
<style>
#box{
width: 500px;
height: 500px;
border: 1px solid #333;
margin: 20px auto;
position: relative;
cursor: url(./images/chui.png),auto;
}
#box img{
position: absolute;
left: 0;
top: 0;
}
</style>
<body>
<div id="box"></div>
</body>
- 整体js
var box = document.getElementById('box');
var timer = setInterval(function(){
var img = document.createElement('img');
img.src = './images/shu.jpg';
img.style.left = getRandom(0,404) + 'px';
img.style.top = getRandom(0,385) + 'px';
img.onclick = function(){
box.removeChild(this);
}
box.appendChild(img);
},3000);
function getRandom(min,max){
return Math.floor(Math.random() * (max-min+1) + min);
}
改写面向对象
属性和方法前面,都要加this,this指向对象
使用:创建对象,并init调用
更改全部js
function Shu (parent,src,x,y){
this.parent = parent;
this.src = src;
this.x = x;
this.y = y;
this.img = null;//占位,在create里面再创建
}
Shu.prototype.init = function(){
this.create();
this.del();
}
Shu.prototype.create = function(){
//创建地鼠
this.img = document.createElement("img");
this.img.src = this.src;
this.img.style.left = this.x + 'px';
this.img.style.top = this.y + 'px';
this.parent.appendChild(this.img);
}
Shu.prototype.del = function(){
var _this = this;//_this指的是Shu对象
this.img.onclick = function(){
//这里的this指的是this.img,所以用_this.parent删其子元素;
_this.parent.removeChild(this);
}
}
// ---------------------------------------- 使用
var box = document.getElementById('box');
var timer = setInterval(function(){
//创建对象,并init调用
var s = new Shu(box,'./images/shu.jpg',getRandom(0,404),getRandom(0,385));
s.init();
},3000);
function getRandom(min,max){
//获取位置随机数,总宽减去图片的宽就是img的left的范围,top同理
//这里的left和top是相对box定位
return Math.floor(Math.random() * (max-min+1) + min);
}
为什么要面向对象写?
如果你需要多个这种效果,并不是说一个页面有多个打地鼠,这只是一个例子,比如说选择项卡,你一个页面需要多次
普通方法就需要每次使用试都写一遍,这样就会造成代码冗余,大片重复代码
面向对象只需要写一次,每次使用只需要创建对象,并init调用,只需要两行
这就是面向对象的意义
但是面向对象特别适合复杂的开发,对于简单的,不太推荐使用面向对象。面对复杂开发时,它特别容易扩展,同时,复用性特别强。