javascript面向对象编程实战 - 手把手教你做小插件

javascript面向对象编程一直都是初学者的难点,都看过很多文章,却没有动手写过,还是理解不深刻,今天我看文章的时候手写了一个及小的插件,正好练练手。

详细的js面向对象编程可以看阮一峰老师的文章 阮一峰-面向对象编程

我正好在看文章时,动手写了一个loading的插件,也可以用在项目中去。分享出来。 github链接

loading效果是这样的:

效果

直接看代码吧,执行特别简单:

var loading = new Loading();

loading.init('container').start(['#5fc6b3', '#d3be87', '#e86c73']);

setTimeout(function () {
    // some ajax
       loading.end()
}, 5000)

只需要事先准备好一个容器

<div id="container"></div>

只有三个api


init() // 参数为容器的id (必须)

start() // 参数为由颜色组成的数组 (非必须)

end() // 无参数

直接看源码吧, 简单得令人发指:

/**
 * @Author zlx
 * @Date 2018/1/17 上午10:42
 */

var Loading = function () {
    this.color = ['#5fc6b3', '#5fc6b3', '#5fc6b3']; // default colors
    this.init = function (id) {
        var container = document.getElementById(id);
        this.container = container;
        return this;
    };

    this.start = function (color) {
        if (!color) {
            color = this.color;
        }
        for (var i = 0; i < 3; i++) {
            var dot = document.createElement('div');
            dot.style.backgroundColor = color[i];
            dot.setAttribute('class', 'dot'+(i+1));
            this.container.appendChild(dot);
        }
        return this;
    };

    this.end = function () {
        var parent = this.container.parentNode;
        if(parent){
            parent.removeChild(this.container);
        }
    }
}

逐一分析:

  • 创建一个叫Loading的构造函数。

  • this.color = ['#5fc6b3', '#5fc6b3', '#5fc6b3']; // default colors给三个小圆点定义三个默认颜色。

  • init方法。

this.init = function (id) {
        var container = document.getElementById(id);
        this.container = container;
        return this;
    };

根据传进来的id来获取到dom元素。并将该dom元素对象赋值给this.container,方便以后使用。最后return this,这里为了方便api实现链式调用,所以return了this。实现了如loading.init('container').start().end();这样的链式调用,这种写法在jquery中很常见。

  • start方法。
this.start = function (color) {
        if (!color) {
            color = this.color;
        }
        for (var i = 0; i < 3; i++) {
            var dot = document.createElement('div');
            dot.style.backgroundColor = color[i];
            dot.setAttribute('class', 'dot'+(i+1));
            this.container.appendChild(dot);
        }
        return this;
    };

这里处理shart’方法传进来的color,是一个数组,如果没有传入,则为我们默认的colors。循环创建3个div,并赋上相应的属性,再添加到container中。

  • end方法
this.end = function () {
       var parent = this.container.parentNode;
       if(parent){
           parent.removeChild(this.container);
       }
   }

最后也很简单,移除这个container。

详细代码见github

这个例子很小,希望对你有帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值