JS中如何实现继承

B继承A,则A为父类,B为子类,继承可以让子类具有父类的各种属性和方法;

继承的实现方法

1、原型链的继承

弊端: 子类的实例对象是使用同一个原型对象;

    function Person() {
    
    
        this.name = "Person";
        this.arr = [1, 2, 3, 4];
    }

    function Child() {
    
    
        this.type = "Child";
    }

    //在Child这个原型上添加Person
    Child.prototype = new Person();
    console.log(new Child());
    //弊端:修改实例对象的值(向数组中添加一个值),另一个实例对象的值也会改变
    const c1 = new Child();
    const c2 = new Child();
    c1.arr.push(5);
    console.log(c1);
    console.log(c2);

在这里插入图片描述

2、使用构造函数继承

弊端: 不能继承原型属性上的方法和属性

    function Person() {
    
    
        this.name = "Person";
        this.arr = [1, 2, 3, 4];
    }
    //不能被继承
    Person.prototype.age = 18;

    function Child() {
    
    
        //构造函数继承不能继承原型属性上的方法和属性
        Person.call(this);
        this.type = "Child";
    }

    console.log(new Child());

在这里插入图片描述

3、组合继承(最常用)

前两个的组合使用,解决了前两个的弊端;

function Person() {
    
    
        this.name = "Person";
        this.arr = [1, 2, 3, 4];
    }

    Person.prototype.age = 18;

    function Child() {
    
    
        Person.call(this);
        this.type = "Child";
    }

    Child.prototype = new Person();
    Child.prototype.constructor = Child;//如果没有这句话,Child的实例对象的constructor是Person
    const c1 = new Child();
    const c2 = new Child();
    console.log(c1.constructor);
    c1.arr.push(5);
    console.log(c1);
    console.log(c2);

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/fangqi20170515/article/details/126671121