event and inheritance in js

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script>
        function EventObject() {
            var eventRepository = {};
            this.attach = function (eventName, handler) {
                eventRepository[eventName] = eventRepository[eventName] || [];
                eventRepository[eventName].push(handler);
            }
            this.fire = function (eventName) {
                var handlers = eventRepository[eventName];
                if (handlers) {
                    for (var i = 0; i < handlers.length; i++) {
                        handlers[i]();
                    }
                }
            }
        }

        function PersonClass(name, age) {
            EventObject.call(this);
            this.name = name;
            this.age = age;

            this.getName = function () {
                return this.name;
            }
        }

        PersonClass.prototype.introduce = function () {
            console.info("I'm " + this.name + ", " + this.age + " years old");
        }


        function EmployeeClass(name, age, emNO, title) {
            PersonClass.call(this, name, age);
            this.emNo = emNO;
            this.title = title;
        }

        EmployeeClass.prototype = new PersonClass();
        EmployeeClass.prototype.finishAJob = function () {
            console.log("I am promoted, I will be given a more important job or rank in the organization that I work for");
            this.fire("promote");
        }

        var emp1 = new EmployeeClass("wj", 18, "2705", "senior");
        var emp2 = new EmployeeClass("wsc", 28, "9705", "senior");

        emp1.introduce();
        emp2.introduce();
        emp2.attach("promote", function () {
            alert("treat my friends!");
        });

        emp2.finishAJob();

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

  

posted @ 2013-03-21 08:31  cnbwang  阅读(163)  评论(0编辑  收藏  举报