<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="calc">
<p>0</p>
<div class="in_group">
<input type="text" value="0" / >
<input type="text" value="0" />
</div>
<div class="btn_group">
<button data-method="plus">+</button>
<button data-method="minus">-</button>
<button data-method="mult">*</button>
<button data-method="dicd">/</button>
</div>
</div>
<script>
const calcEl = document.getElementById('calc')
const utils = {
delSpace(value) {
return value.replace(/\s+/g, '')
},
toNum(value) {
return Number(value) || 0
}
}
// class computed {
// plus(a,b) {
// return a +b
// }
// minus(a,b) {
// return a - b
// }
// mult(a,b) {
// return a * b
// }
// dicd(a,b) {
// return a / b
// }
// }
// 装饰器
const computed = target => {
target.prototype.plus = function (a, b) {
return a + b
}
target.prototype.minus = function (a, b) {
return a - b
}
target.prototype.mult = function (a, b) {
return a * b
}
target.prototype.dicd = function (a, b) {
return a / b
}
}
class calcObj {
constructor(el) {
// super() // 继承后这个要写
this.el_name = 'calcEl'
this.result_p = el.getElementsByTagName('p')[0]
this.btn_group = el.getElementsByClassName('btn_group')[0]
this.inputs = el.getElementsByTagName('input')
}
init() {
this.bindEvent()
}
bindEvent() {
this.btn_group.addEventListener('click', this.btnClick.bind(this), false)
}
render(method, fval, sval) {
this.result_p.innerText = this[method](fval, sval)
}
btnClick(ev) {
const e = ev || window.event
const tar = e.target || e.srcElement
const tagName = tar.tagName.toLowerCase()
if (tagName === 'button') {
const method = tar.dataset.method
const fval = utils.toNum(utils.delSpace(this.inputs[0].value))
const sval = utils.toNum(utils.delSpace(this.inputs[1].value))
console.log(fval, sval)
// this.result_p.innerText = this[method](fval,sval)
this.render(method, fval, sval)
// switch (method) {
// case 'plus':
// this.result_p.innerText = fval + sval
// break
// case 'minus':
// this.result_p.innerText = fval - sval
// break
// case 'mult':
// this.result_p.innerText = fval * sval
// break
// case 'dicd':
// this.result_p.innerText = fval / sval
// break
// default:
// break
// }
}
}
}
computed(calcObj)
const init = () => {
new calcObj(calcEl).init()
}
init()
</script>
</body>
</html>
面向对象计算器(简单版)
最新推荐文章于 2022-10-21 21:21:49 发布