zengdj

点滴经验,源自实践

博客园 首页 新随笔 联系 订阅 管理
方法2基本上是方法1的封装,提供了一个专门的方法用于子类的继承,同时克服了方法1的两个缺点:
// namespace 
JsDev = {};

JsDev.extend = function(subClass, baseClass) {
   function inheritance() {}
   inheritance.prototype = baseClass.prototype;

   subClass.prototype = new inheritance();          // 改变子类的原型,使其原型与父类原型串连起来
   subClass.prototype.constructor = subClass;       // 改变子类的构造函数
   subClass.baseConstructor = baseClass;            // 保存对基类构造函数的引用,以便在子类中调用
   subClass.superClass = baseClass.prototype;       // 保存对父原型的引用
}

//Person class
function Person(first, last) {
    this.first = first;
    this.last = last;
}

Person.prototype.toString = function() {
    return this.first + " " + this.last;
};


//Employee class
function Employee(first, last, id) {
    Employee.baseConstructor.call(this, first, last);  // 调用父类中的构造函数
    this.id = id;
}

// subclass Person
JsDev.extend(Employee, Person);

Employee.prototype.toString = function() {
    return Employee.superClass.toString.call(this) + ": " + this.id;  // 调用父类中被覆盖的同名方法
};

//Manager
function Manager(first, last, id, department) {
    Manager.baseConstructor.call(this, first, last, id);
    this.department = department;
}

// subclass Employee
JsDev.extend(Manager, Employee);

Manager.prototype.toString = function() {
    return Manager.superClass.toString.call(this) + ": " + this.department;
};
posted on 2007-09-14 05:50  DingJun  阅读(379)  评论(1编辑  收藏  举报