Friday, September 28, 2012

Javascript structural pattern

1. Prototype Pattern,

<script type="text/javascript">
    var Calculator = function (id) {
        this.id = id;
    };
    Calculator.prototype = {
        add: function (x, y) {
            var result = x + y;
            $(this.id).html("<br>" + result + "</br>");
        },
       
        multiply: function (x, y) {
            var result = x * y;
            $(this.id).html("<br>" + result + "</br>");
        }
    };

    $(document).ready(function () {
        var c = new Calculator('#a');
        c.add(12, 32);
        c.id = '#b';
        c.multiply(2, 10);
       
    });
</script>

<div id="a"></div>
<div id="b"></div>

Also arguments can be used for variable length of parameters within function to be able to do things like test(a), test(a, b), test(a, b, c) etc...

2. Module Pattern - to hide the private property/method

var Calculator = function(id) {
    //private members
    var id = id;
    //public members
    return {
         add: function (x, y) {
               $(id).html( x+y);
         }
    };
};

Client:
var c = new Calculator('#a');
c.add(3, 5);

3. Revealing Module Pattern
var calculator = function(id) {
       var id = id;
       var doAdd = function (x, y) { $(id).html (x + y);
       return {
             add  : doAdd;
       }
         
}('#a'); //use this to self invoking.

Client:
calculator.add(3, 5);

4. Revealing Prototype Pattern
var Calculator = function (eq) {
    //this. variables.
};

Calculator.prototype = function() {
     // private members
     var doAdd = function (x, y) {return x + y;}
     return {
           add : doAdd;
     };
}();


No comments: