在面向对象编程中,类B可以继承自类A,我们将A称为父类,B类称为子类.B的实例从A继承了所有的实例方法.类B可以定义自己的实例方法.有些方法可以重载类A中的同名方法,如果B的方法重载了A的方法,B中重载方法就可能会调用A中的重载方法,这种做法称之为方法链,子类的构造函数B()有时需要调用父类的构造函数A()
举例
首先创建两个工具函数
inherit()函数用来让原型对象继承创建一个新对象
extend()函数用来枚举属性对象
function inherit (p) { if(p == null) throw TypeError(); if(Object.create) return Object.create(p); var t = typeof p; if(t !== "object" && t !== "function") throw TypeError(); function f() {}; f.prototype = p; return new f(); }
function extend (o, p) { for (prop in p) { o[prop] = p[prop]; } return o; }
开始:定义子类
创建一个简单的子类
function defineSubclass(superclass, // 父类的构造函数 constructor,// 新的子类构造函数 methods, // 实例方法:复制至原型中 statics) // 类属性:复制至构造函数中 { // 建立子类的原型对象 constructor.prototype = inherit(superclass.prototype); constructor.prototype.constructor = constructor; // 像对常规类一样复制方法和类属性 if (methods) extend(constructor.prototype, methods); if (statics) extend(constructor, statics); // 返回这个类 return constructor; };
创建一个构造函数父类 并添加一个原型方法toString后面会说到 注意这是定义在父类的原型中
function Set () {} Set.prototype.toString = function () { alert("我的子类调用到我了") }
Set.prototype.add = function () {
alert("父类中的add方法")
}
再定义一个子类构造函数 并添加一个原型方法add
function SetChildren (){}
SetChildren.prototype.add = function () {
alert("覆盖父类的add方法");
}
defineSubclass(Set,SetChildren,SetChildren.prototype,{"a":"1"}) var childClass = new SetChildren(); console.log(childClass.add()) // 子类覆盖了父类的add console.log(childClass.toString()) // 子类虽然没有定义,但是他会调用父类的toString
也可以通过父类构造函数的方法来做到这一点
Function.prototype.extend = function (constructor, methods, statics){ return defineSubclass(this,constructor,methods,statics); }
今天就到这里 谢谢大家