zengdj

点滴经验,源自实践

博客园 首页 新随笔 联系 订阅 管理
几天学习后总结一下Javascript关于继承的几种方法,基本都是关于原型法的,先看最简单的。

定义基类Person:
function Person(first, last)
{
   
this.first = first;
   
this.last = last;
}


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

定义子类Employee:
function Employee(first, last, id)
{
   
this.id = id;
}


Employee.prototype
= new Person();
Employee.prototype.constructor
= Employee;

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

通过改变Employee.prototype的原型让Employee继承于Person类:Employee.prototype = new Person();

再定义子类Manager:
function Manager(first, last, id, department) {
   
this.department = department;
}


Manager.prototype
= new Employee();
Manager.prototype.constructor
= Manager;

Manager.prototype.toString
= function()
{
    return this.first + " " + this.last + ": " + this.id
 + ": " + this.department;
}
;
用同样的方法让Manager类继承于Employee类。
缺点:
1,不能调用基类的构造函数以便初始化。
2,不能调用被覆盖的基类中的同名方法。
posted on 2007-09-14 04:27  DingJun  阅读(413)  评论(0编辑  收藏  举报