JavaScript的寄生组合式继承

来源:互联网 发布:unity3d程序员 编辑:程序博客网 时间:2024/04/27 14:48

寄生组合式继承示例

第一篇博客,留个纪念

//父类构造函数function Super(name){    this.name = name;    this.funcName = "Super";    this.func = "super";}Super.prototype.sayName = function (){ alert(this.name); }Super.prototype.sayFuncName = function (){ alert(this.funcName); }//子类构造函数function Sub(name,age){    Super.call(this,name);    this.age = age;    this.funcName = "Sub";}//继承函数function inheritPrototype(Sub,Super){    //中间实例化对象    var a = Object(Super.prototype);    //重写该对象的构造函数指针,指向Sub函数    a.constructor = Sub;    //Sub的原型指向实例化对象a    Sub.prototype = a;}//调用继承函数,实现原型链构造inheritPrototype(Sub,Super);/*----------一定要在调用继承函数之后添加,如果放在继承函数之前,随着原型的替换,函数会undefined。----------*///添加子类方法Sub.prototype.sayAge = function (){ alert(this.age); }Sub.prototype.sayFuncName = function (){ alert(this.funcName); }//测试代码var subTest = new Sub("lulu",20);subTest.sayName(); //lulusubTest.sayAge(); //20subTest.sayFuncName(); //Subalert(subTest.func); //super