JS中面向对象的多种继承方式

JS本身是基于面向对象开发的编程语言,面向对象开发中最重要的一个概念就是类。

类具有三大特性:封装、继承、多态

封装:类也是个函数,函数的目的是把一个功能代码进行封装,以此实现“低耦合高内聚”

多态:重载和重写

  重写:子类重写父类上的方法(伴随着继承运行的)

  重载:相同的方法,由于参数或者返回值的不同,具备不同的功能(js中不具备严格意义上的重载,js中的重载,在方法内部进行逻辑判断,根据参数的不同的功能)

继承:子类继承父类的属性和方法。在js中的继承和其他编程语言不太一样

继承的目的:让子类的实例同时也具备父类中私有的属性和公共方法

js中实现继承的方法:原型继承

1、原型继承:让子类的原型等于父类的实例

function parent() {
    this.x = 100;
}
parent.prototype.getX = function getX() {
    return this.x
}

function son() {
    this.y = 200;
}
son.prototype = new Parent(); // 实现继承关键
son.prototype.getY = function getY() {
    return this.y
}

let c1 = new son();
console.log(c1);

原型继承的特点:

父类中私有的和公有的方法,最后都变为子类公有的

原型链继承不会把父类的属性和方法拷贝给子类,而是让子类实例基于__proto__原型链找到自己定义的属性和方法

c1.__proto__.xxx = xxx,修改子类原型(原有父类的一个实例)中的内容,对子类的其他实例有影响,但是对父类的实例不会有影响

son.prototype.__proto__ === parent.prototype

2、call继承

function parent() {
    this.x = 100;
}
parent.prototype.getX = function getX() {
    return this.x
}

function son() {
    this.y = 200;
    parent.call(this); // 关键点
}
son.prototype.getY = function getY() {
    return this.y
}

let c1 = new son();
console.log(c1);

call继承特点:

改变this,让父类中的this变成子类的一个实例,这样父类中的私有属性变成了子类实例的私有属性

只能继承父类中的私有的,不能继承父类中公共的

我们需要的是父类私有的变为子类私有的,父类公有的变为子类公有的

3、组合式继承(call继承 + )

function parent() {
    this.x = 100;
}
parent.prototype.getX = function getX() {
    return this.x
}

function son() {
    this.y = 200;
    parent.call(this); // 关键点
}
son.prototype.__proto__ = parent.prototype // 关键点
// 不支持__proto__的浏览器中使用Object.create(对象)
// Object.create()创建一个空对象,让其原型(__proto__)指向这个对象
// 上述代码就变成
son.prototype = Object.create(parent.prototype);

son.prototype.constructor = son; son.prototype.getY
= function getY() { return this.y } let c1 = new son(); console.log(c1);

核心思想:原型继承的另外一个写法,用的不是父类的实例,而是修改子类的原型,指向父类的prototype

es6中的继承extends类似于寄生组合继承

class parent {
    constructor() {
        // 私有属性
        this.x = 100;
    }
    // parent.prototype.getX = fuunction ...
    // 往原型上写方法
    getX() {}
}

class son extends parent {
    constructor() {
        super();
        this.y = 200;
    }
    getY() {
        return this.y
    }
}

super()执行,类似于parent.prototype.constructor.call(this),如果我们往super中传参数,super(100, 200),类似于把parent中的constructor执行,传递了100和200

原文地址:https://www.cnblogs.com/zmyxixihaha/p/14608169.html