面向对象-(计数器,矩形)

// html
<div id="main"></div>

// js

function Rect (options) {
  this._init(options)
}
Rect.prototype = {
  // 属性
  _init: function (options) {
    // 父标签
    this.parentId = options.parentId
    // 位置
    this.left = options.left || 100
    this.top = options.top || 100
    // 自身的属性
    this.width = options.width || 100
    this.height = options.height || 50
    this.bgColor = options.bgColor || '#000'
    this.borderRadius = options.borderRadius || 0
    this.border = options.border || 'none'
  },

  // 行为
  render: function () {
    // 1.获取父标签
    var parentEle = document.getElementById(this.parentId)
    // 2.创建 矩形标签
    var ele = document.createElement('div')
    parentEle.appendChild(ele)

    ele.style.position = 'absolute'
    ele.style.left = this.left + 'px'
    ele.style.top = this.top + 'px'

    ele.style.width = this.width + 'px'
    ele.style.height = this.height + 'px'

    ele.style.backgroundColor = this.bgColor
    ele.style.border = this.border
    ele.style.borderRadius = this.borderRadius + 'px'
  }
}

var rect = new Rect({
  parentId: 'main',
  width: 500,
  height: 300,
  bgColor: 'pink'
})
// console.log(rect)
rect.render()

 计时器 (函数链式调动)

var Caculator = {
        result: 0,
        jia: function (num) {
            this.result += num;
            return this;
        },
        jian: function (num) {
            this.result -= num;
            return this;
        },
        cheng: function (num) {
            this.result *= num;
            return this;
        },
        chu: function (num) {
            this.result /= num;
            return this;
        },
        log: function () {
            console.log(this.result);
            return this;
        },
        clean: function () {
            this.result = 0;
            return this;
        }
    };
    // (6 + 6) * 2 / 3
    Caculator.jia(6).jia(6).cheng(2).chu(3).log();
    Caculator.clean().jia(2).log();

 

posted @ 2019-02-11 15:14  慕斯undefined  阅读(201)  评论(0编辑  收藏  举报