The Prototype Pattern

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = function () {
            var c = new Calculator('eq');
            c.add(2, 3);
        };

        //if the fouction is a constractor, then the first character "C" should be Upper case.
        //Constructor defines properties and inits object.
        var Calculator = function (eq) {
            this.eqCtrl = document.getElementById(eq);
        };

        //Prototype defines functions using JSON syntax
        Calculator.prototype = {
            add: function (x, y) {
                var val = x + y;
                this.eqCtrl.innerHTML = val;
            },

            subtract: function (x, y) {
                var val = x - y;
                this.eqCtrl.innerHTML = val;
            }
        };
    </script>
</head>
<body>
    <div id='eq'>
    </div>
</body>
</html>

 

posted on 2013-04-27 13:29  hhenliang  阅读(101)  评论(0编辑  收藏  举报

导航