JS中的继承

来源:互联网 发布:linux怎么新建文件 编辑:程序博客网 时间:2024/06/09 21:19

一、原型继承

function surperClass () {    this.name= 'hello';}surperClass.prototype.getSurperName = function(){    return this.name;};function subClass(name){    this.name = 'world';}//继承了surperClasssubClass.prototype = new surperClass();subClass.prototype.getsubClassName = function(){    return this.name;};var instance = new subClass();console.log(instance.getSurperName);  //hello

原型链虽然很强大,可以用它来实现继承,但它也存在一些问题。在通过原型来实现继承时,原型实际上会变成另一个类型的实例。于是,原先的实例也就顺理成章地变成了现在的原型属性了

二、借用构造函数继承

function surperClass(name){    this.name = name;    this.color = ['red','white','yellow'];}function subClass(){    surperClass.call(this,'goodnight');}var instance = new subClass();instance.push('blue');alert(instance.color); // red ,white,yellow ,bluevar instance2 = new subClass();alert(instance2.color); // red white yellow

三、组合继承

function surperClass(name){    this.name = name;    this.color = ['red','white','yellow'];}surperClass.prototype.getName = function(){    // body...     return name;};function subClass(age){    surperClass.call(this,'goodnight');    this.age = age;}subClass.prototype = new surperClass();subClass.prototype.getAge = function(){    // body...     return this.age;};var instance = new subClass(23);alert(instance.getName()); //goodnightalert(instance.getAge());   // 23

四、原型式继承

function object (o) {    function f () {        // body...     }    f.prototype = o;    return new f();}var persion = {    name:'nick',    friends:['lily','Rob']}var anotherpersion = Object(persion);anotherpersion.name; //'nick'anotherpersion.friends.push('134');alert(persion.friends) //lily rob 134

五、寄生式继承

function object (o) {    function f () {        // body...     }    f.prototype = o;    f.getName = function () {        /* body... */    }    return new f();}

六、寄生组合式继承

function inhreitProperty (subClass,surperClass) {    // body...     //复制一份父类的原型副本保存在P中    var p = object(surperClass.prototype);    //修正因为重写子类原型导致子类的constructor属性被修改    p.constructor = subClass;    //设置子类的原型    subClass.prototype = p;}