JS/ES针对性总结:继承?class?

68 阅读2分钟

继承(ES5)

  1. 继承是一种实现代码重用和创建对象之间关联的重要机制

  2. 在ES5中,使用组合继承,组合继承 === 构造函数继承 + 原型继承

  3. 构造函数继承

    • 子类继承父类属性,使用 parent.call(this, attr) 来继承父类的属性,这里的this是将父类构造函数的作用域指向子类实例对象
  4. 原型继承

    • 子类继承父类方法,使用 children.prototype = new parent() 来继承父类原型上的方法

      (注意:这里不可以直接将父类的原型对象赋值给子类的原型对象 children.prototype = parent.prototype ,这样子类就会随父类原型的改变而改变)

    • 还可以使用 children.prototype = Object.create(parent.prototype)

// 父类构造函数
function parent(name) {
    this.name = name
    console.log(this) // 打印:parent {name: 'wanghaoyang'}
}

// 父类原型对象中添加what方法
parent.prototype.what = function () {
    console.log('sunxiaochuan')
}

// 子类构造函数
function children(name, age) {
    parent.call(this, name) // 构造函数继承(属性继承)。执行父类,打印:children {name: 'xujingyu'}
    this.age = age
}

children.prototype = Object.create(parent.prototype) // 原型继承(方法继承)

// 父类创建实例对象,不受影响,自己玩自己的
let obj1 = new parent('wanghaoyang')

// 子类创建实例对象,这里都正常
let obj2 = new children('xujingyu', 36)
obj2.what()
// 打印:sunxiaochuan

说一下class

  1. 面向对象编程,class定义一个类,内部有一个构造器函数constructor,可以使用构造函数创建实例对象

  2. constructor是用于创建和初始化对象,一般是把构造函数中传来的参数绑到this上,这个this指向的是class类,然后再在类中定义其他方法

  3. class的优点:

    1. 定义类更加简洁,符合面向对象编程
    2. 可以继承其他类,子类可以继承父类,实现代码的复用
    3. 易于维护和优化,class定义的属性和方法都挂载在原型对象上(prototype),避免创建多个属性和方法

继承(ES6)

  1. 在ES6中,构造函数继承(属性继承)使用 super(attr) (好像是Java中的方法)

  2. 原型继承(方法继承)使用 extends 关键字直接定义

// 父类构造函数
class parent {
    constructor(name) {
        this.name = name
    }
    what() {
        console.log('sunxiaochuan')
    }
}

// 子类构造函数
class children extends parent { // extends 方法继承
    constructor(name, age) {
        super(name) // 属性继承
        this.age = age
    }
    what() {
        super.what() // 直接调用父类构造函数中的方法
        console.log('shitiaogou')
    }
}

// 父类创建实例对象
let obj1 = new parent('wanghaoyang')

// 子类创建实例对象
let obj2 = new children('xujingyu', 36)
obj2.what()
// 打印:sunxiaochuan
//      shitiaogou