OOP Calculator
Object-oriented calculator implementation using straight Javascript.
HTML
<h2>OOP Calculator</h2>
<div id="calculator">
<form action='index.html' method='post' name='calc'>
<input type='text' disabled='true' name='output' id='output' value="0" />
<table id="buttontable">
<tr>
<td>
<input type='button' value='C' />
</td>
<td>
<input type='button' value='BS' disabled />
</td>
<td>
<input type='button' value='MR' disabled />
</td>
<td>
<input type='button' value='MC' disabled />
</td>
<td>
<input type='button' value='M+' disabled />
</td>
</tr>
<tr>
<td>
<input type='button' value='7' />
</td>
<td>
<input type='button' value='8' />
</td>
<td>
<input type='button' value='9' />
</td>
<td>
<input type='button' value='*' />
</td>
<td>
<input type='button' value='tan' />
</td>
</tr>
<tr>
<td>
<input type='button' value='4' />
</td>
<td>
<input type='button' value='5' />
</td>
<td>
<input type='button' value='6' />
</td>
<td>
<input type='button' value='-' />
</td>
<td>
<input type='button' value='cos' />
</td>
</tr>
<tr>
<td>
<input type='button' value='1' />
</td>
<td>
<input...
CSS
#calculator {
border: solid black 1px;
display: inline-block;
padding: 4px;
border-radius: 4px;
}
#calculator input[type="text"] {
text-align: right;
}
#buttontable {
position: relative;
}
#buttontable input {
width: 32px;
height: 32px;
padding: 0px;
}
JavaScript
(function () {
"use strict";
var $ = function (item) {
return typeof item === 'string' ? document.getElementById(item) : item;
};
var hookEvent = window.addEventListener ? function (target, name, handler) {
$(target).addEventListener(name, handler);
} : function (target, name, handler) {
$(target).attachEvent('on' + name, handler);
};
var bind = function (target, callback) {
var self = target;
return function (event) {
return callback.call(self, event);
};
};
var Calc = function (container, buttons, output) {
this.result = 0;
this.operand = '';
this.operation = '';
this.memory = 0;
this.buttons = $(buttons);
this.output = $(output);
this.container = container;
hookEvent(this.buttons, 'click', bind(this, this.on_button_pressed));
hookEvent(window, 'keypress', bind(this, this.on_key_pressed));
};
Calc.prototype = {
apply_and_set_operation: function (next_op) {
if (next_op === 'C') {
this.result = 0;
this.operand = '';
this.operation = '';
return;
}
if (this.operand !== '') {
switch (this.operation) {
case '':
this.result = +this.operand;
break;
case '+':
this.result += +this.operand;
break;
case '-':
this.result -= +this.operand;
break;
case '*':
this.result *= +this.operand;
break;
case '/':
this.result /= +this.operand;
break;
}
}
this.operation = next_op !== '=' ?...