JS中繼承

js中的繼承無論是在面試還是在實際應(yīng)用中都是一個高頻的知識點,總結(jié)梳理下。

方法1.通過構(gòu)造函數(shù)實現(xiàn)繼承

/* 
    借助構(gòu)造函數(shù)實現(xiàn)繼承
 */

 function Person(name) {
     this.name = name;
 }
 Person.prototype.sayName = function () {
     console.log(this.name);
 }

 function Man(name) {
     Person.call(this,name);
 }

 var liming = new Man('liming');

console.log(liming.sayName())

通過構(gòu)造函數(shù)繼承的這種方法的缺點就是不能繼承父類原型上的方法。

方法2.通過原型鏈實現(xiàn)繼承

/* 
    借助原型鏈實現(xiàn)繼承
 */

function Perant() {
    this.name = 'parent';
    this.play = [1,2,3];
}

function Child() {
    this.type = 'child2';
}

Child.prototype = new Perant();

var s1 = new Child();
var s2 = new Child();

console.log(s1.play,s2.play);//[1,2,3] [1,2,3]

s1.play.push(4);

//s1的play添加新元素后,s2中的play也添加了新元素
console.log(s1.play, s2.play);//[1,2,3,4] [1,2,3,4]

這種方法的缺點就是每個實例都引用了父類的對象,所以一個實例修改繼承對象的屬性,所有的實例引用的父類屬性就也受到了修改。

方法3.組合繼承

   function Parent(name) {
        this.name = name;
    }

    Parent.prototype.sayName = function () {
        return this.name
    }

    function Child(name, age) {
        Parent.call(this, name);
        this.age = age;
    }

    Child.prototype = Object.create(Parent.prototype);
    Child.prototype.constructer = Child;


    var p1 = new Child('limming');

    console.log(p1.sayName());

組合繼承的這種方式很好的解決構(gòu)造函數(shù)繼承和原型鏈繼承的方法的兩種缺點,組合繼承中通常將公用的方法放在原型鏈上,私有的屬性放在構(gòu)造函數(shù)中。
組合繼承中需要注意的是不忘將子類的原型上的contructor重新指向子類

 Child.prototype.constructer = Child;

Object.create方法會使用指定的原型對象及其屬性去創(chuàng)建一個新的對象。這API是IE9中才支持,兼容的寫法如下

funciton F(){}
F.prototype = Parent.protoype;
Child.prototype = new F();

方法4.ES6中的繼承

class Parent {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    say() {
        console.log(this.name + ':我是社會主義接班人');
    }
}

class Child extends Parent {
    constructor(name, age, sex) {
        super(name, age);
        this.sex = sex;
    }
    printSex() {
        console.log(this.sex);
    }
}

var ruoyu = new Child('小明', '27', '男');

ruoyu.say();
ruoyu.printSex();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容