面向对象,打地鼠的面向对象写法

打地鼠,普通和面向对象写法

面向对象特别适合复杂的开发,对于简单的,不太推荐使用面向对象。

这里只是举一个小例子解释什么是面向对象。

目录
在这里插入图片描述

普通写法
  • 样式以及布局:
<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调用,只需要两行

这就是面向对象的意义

但是面向对象特别适合复杂的开发,对于简单的,不太推荐使用面向对象。面对复杂开发时,它特别容易扩展,同时,复用性特别强。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值