Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 6 299



  1. Modify the numberClick, plusClick, minusClick, clearEntry, and clear functions to define
    these functions on the Calculator prototype.
    The CalculatorLibrary.js should look like the following.
    ///


(function () {
this.calculatorNamespace = this.calculatorNamespace || {};
var ns = this.calculatorNamespace;

function initialize() {
for (var i = 0; i < 10; i++) {
document.getElementById('btn' + i)
.addEventListener('click', numberClick, false);
}
txtInput = document.getElementById('txtInput');
txtResult = document.getElementById('txtResult');

document.getElementById('btnPlus')
.addEventListener('click', plusClick, false);
document.getElementById('btnMinus')
.addEventListener('click', minusClick, false);
document.getElementById('btnClearEntry')
.addEventListener('click', clearEntry, false);
document.getElementById('btnClear')
.addEventListener('click', clear, false);
clear();
}

ns.Calculator = (function () {

function Calculator() {
}

Calculator.prototype.numberClick = function () {
txtInput.value = txtInput.value == '0'?
this.innerText : txtInput.value + this.innerText;
};

Calculator.prototype.plusClick = function () {
txtResult.value = Number(txtResult.value) + Number(txtInput.value);
clearEntry();
};

Calculator.prototype.minusClick = function () {
txtResult.value = Number(txtResult.value) - Number(txtInput.value);
clearEntry();
};

Calculator.prototype.clearEntry = function () {
txtInput.value = '0';
};

Calculator.prototype.clear = function () {
Free download pdf