06 - Revealing Prototype Pattern (SJC)

by Diya_Khan

HTML

<div id="output"></div>
<div id="output1"></div>

JavaScript

//pattern most used these days
var Calculator = function(elmId) {
    this.element = document.getElementById(elmId);
};

Calculator.prototype = function() {
    var addValues = function(x, y) {
        return x + y;
    },
        add = function(x, y) {
            this.element.innerHTML = addValues(x, y);
        };
    return {
        add: add
    };

}();

var calc = new Calculator('output');
calc.add(4, 4);

Calculator.prototype.add = function(x, y) {
    var sum = x + y;
    this.element.innerHTML = x + "+" + y + "=" + sum;
};

var calc1 = new Calculator('output1');
calc1.add(4, 4);