Sunday, September 28, 2014

How to override base class methods in JavaScript (when used with "prototype")

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
        //DEMO: Overriding methods using prototype

        //create parent class
        var Person = function (vId, vName) {
            this.Id = vId;
            this.Name = vName;
        };

        Person.prototype.Display = function () {
            alert("Id=" + this.Id.toString() +
                    ", Name=" + this.Name);
        }

        //create new class
        var Emp = function (vId, vName, vOfficeMail) {
            if (arguments.length < 3) return;
            Person.call(this, vId, vName)
            this.OfficeEmail = vOfficeMail;
        };

        //make Emp class as a child of Person class
        Emp.prototype = new Person();
        Emp.prototype.constructor = Emp;
        //overriding method
        Emp.prototype.Display = function () {
            alert("Id=" + this.Id.toString() +
                    ", Name=" + this.Name +
                    ", OfficeMail=" + this.OfficeEmail);
        }

        //create instance of child class
        var oEmp = new Emp(1001, "Jag", "a@a.com"); //using Child's constructor
        //call display method in child class
        oEmp.Display();

        //create instance of parent class
        var oPerson = new Person(1002, "Chat"); //using Parent's constructor
        //call display method in parent class
        oPerson.Display();


    </script>
</head>
<body>
</body>
</html>

No comments: