JS中继承

js中的继承无论是在面试还是在实际应用中都是一个高频的知识点,总结梳理下。

方法1.通过构造函数实现继承

/* 
    借助构造函数实现继承
 */

 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())

通过构造函数继承的这种方法的缺点就是不能继承父类原型上的方法。

方法2.通过原型链实现继承

/* 
    借助原型链实现继承
 */

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());

组合继承的这种方式很好的解决构造函数继承和原型链继承的方法的两种缺点,组合继承中通常将公用的方法放在原型链上,私有的属性放在构造函数中。
组合继承中需要注意的是不忘将子类的原型上的contructor重新指向子类

 Child.prototype.constructer = Child;

Object.create方法会使用指定的原型对象及其属性去创建一个新的对象。这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();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容