JavaScriptで10の練習問題 #4
簡易電卓
0で割ったときの処理を作り込むのは、本質的では無いのでやめておく。
function Calculator(display) { this.display = display; this.display.value = 0; this.input = 0; this.total = 0; this.tmpOpe = ''; this.tFlag = false; } Calculator.prototype = { setEvent : function (item) { switch (item.value) { case '+': case '-': case '*': case '/': this.eventOperator(item.value); break; case '=': this.eventTotal(); break; case 'C': this.eventAllClear(); break; default: this.eventNumber(item.value); } }, eventNumber : function (v) { if (v == 0 && this.input == 0) { return; } this.input = this.input == 0 ? v : this.input + v; this.display.value = this.input; }, eventOperator : function (v) { if (this.input) { this.total = this.tmpOpe ? this.getTotal() : this.input; } this.input = ''; this.tmpOpe = v; this.display.value = this.total; }, eventTotal : function () { if (this.tmpOpe === '') { return; } this.display.value = this.total = this.getTotal(); this.input = 0; this.tFlag = true; }, eventAllClear : function () { this.display.value = this.input = 0; this.total = 0; this.tmpOpe = null; }, getTotal : function () { var total = Number(this.total); var input = Number(this.input); return this.tmpOpe === '+' ? total + input : this.tmpOpe === '-' ? total - input : this.tmpOpe === '*' ? total * input : this.tmpOpe === '/' ? total / input : this.display.value; } } var study_04 = function () { var calc = new Calculator(document.getElementById('calcDisplay')); var items = document.getElementById('calc').getElementsByTagName('button'); for (var i = 0, len = items.length; i < len; i++) { items[i].onclick = function () { calc.setEvent(this); } } }
オブジェクトとprototypeを何となく理解したので使ってみた。
小数点が無かったり電卓としては不便だけど、この練習問題で得たものは多かったので良し。
今回使ったHTML
<div><input type="text" id="calcDisplay" value=""></div> <table id="calc"> <tbody> <tr> <td><button value="7">7</button></td> <td><button value="8">8</button></td> <td><button value="9">9</button></td> <td><button value="*">×</button></td> </tr> <tr> <td><button value="4">4</button></td> <td><button value="5">5</button></td> <td><button value="6">6</button></td> <td><button value="/">÷</button></td> </tr> <tr> <td><button value="1">1</button></td> <td><button value="2">2</button></td> <td><button value="3">3</button></td> <td><button value="-">−</button></td> </tr> <tr> <td><button value="0">0</button></td> <td><button value="C">C</button></td> <td><button value="=">=</button></td> <td><button value="+">+</button></td> </tr> </tbody> </table>