几天学习后总结一下Javascript关于继承的几种方法,基本都是关于原型法的,先看最简单的。
定义基类Person:
定义子类Employee:
通过改变Employee.prototype的原型让Employee继承于Person类:Employee.prototype = new Person();
再定义子类Manager:
缺点:
1,不能调用基类的构造函数以便初始化。
2,不能调用被覆盖的基类中的同名方法。
定义基类Person:
function Person(first, last)
{
this.first = first;
this.last = last;
}
Person.prototype.toString = function()
{
return this.first + " " + this.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;
};
{
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类。 this.department = department;
}
Manager.prototype = new Employee();
Manager.prototype.constructor = Manager;
Manager.prototype.toString = function()
{
return this.first + " " + this.last + ": " + this.id + ": " + this.department;
};
缺点:
1,不能调用基类的构造函数以便初始化。
2,不能调用被覆盖的基类中的同名方法。