ES6 Class继承

class是ES6新增的一个属性,目的就是为了让定义类更加方便

之前我们定义一个类是这样的

    function Student (name) {
        this.name = name
    }
    Student.prototype.hello = function () {
        console.log('Hello ' + this.name)
    }

现在我们class来改编一下

    class Student {
        constructor (name) {
            this.name = name
        }
        hello () {
            console.log('Hello ' + this.name)
        }
    }

比较一下我们可以发现,class的定义包含了构造函数constructor和定义在原型对象上的函数hello()(注意没有function关键字),这样就避免了Student.prototype.hello = function () {...}这样分散的代码
创建一个Student的代码和之前是一样的

    let xiaoming = new Student('小明')
    console.log(xiaoming.name)//小明
    xiaoming.hello()//Hello小明

class继承

class定义对象还有一个非常大的好处就是继承变的方便了。使用原型继承Student的时候我们需要先创建一个空的对象,让空对象的等于Student的所有属性,然后再将需要继承的对象等于这个空对象,代码量是非常复杂的。现在,原型继承的中间对象,原型对象的构造函数等等都不需要考虑了,直接通过extends来实现:

    class PrimaryStudent extends Student{
        construct(name,age){
            super(name)
            this.age = age
        }
        myAge(){
            console.log('my age is ' + this.age)
        }
    }

创建一个PrimaryStudent的代码和之前是一样的

    let xiaohong = new PrimaryStudent('小红',18)
    console.log(xiaohong.name)//小红
    xiaohong.myAge()//my age is 18

注意PrimaryStudent的定义也是class关键字实现的,而extends则表示原型链对象来自Student。子类的构造函数可能会与父类不太相同.例如:PrimaryStudent需要namegrade两个参数,并且需要通过super(name)来调用父类的构造函数,否则父类的name属性无法正常初始化。

PrimaryStudent已经自动获得了父类Studenthello方法,我们又在子类中定义了新的myAge方法。

ES6引入的class和原有的JavaScript原型继承有什么区别呢?
没有什么区别,用class的好处就是极大地简化了原型链代码

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-08
  • 2021-09-14
  • 2019-01-09
  • 2021-10-19
猜你喜欢
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
  • 2021-08-01
  • 2021-09-06
  • 2021-09-07
  • 2021-11-12
相关资源
相似解决方案