03 - Prototype Pattern (SJC)

by Diya_Khan

HTML

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

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

JavaScript

//Prototype class
//Advantages:overriding,functions are created only once in memory
//Disadvantages:resolving this issues, no encapsulation

//Constructor with properties
var Calculator = function(elmId) {
    this.element = document.getElementById(elmId);
};

//Methods implementation with prototype
Calculator.prototype = {
    add: function(x, y) {
        var sum = x + y;
        this.element.innerHTML = sum;
    }
};

//Creating object
var calc = new Calculator('output');
//Call method of object
calc.add(5, 3);

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

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