← 返回首页
Javascript基础教程(二十八)
发表时间:2020-03-31 11:55:16
讲解Javascript的class继承

ES6引入class后,使用class定义对象的一个最大的好处是继承更方便了。Class 之间可以通过extends关键字实现继承, 这比 ES5 的通过修改原型链实现继承, 要清晰和方便很多。

例如:

<script>
    class Animal{
        constructor(weight,height){
            this.weight = weight;
            this.height = height;
        }
    }

    class Person extends Animal{
        constructor(name,gender,weight,height){
            super(weight,height);
            this.name = name;
            this.gender = gender;
        }

        thinking(){
            console.log(this.name+" is thinking now!");
        }
    }

    let p = new Person('张三','男',65,170);
    console.log(p);
    p.thinking();
</script>
运行结果:
Person {weight: 65, height: 170, name: "张三", gender: "男"}
张三 is thinking now!

我们可以看出其类构造方法调用顺序与super关键字的用法都与java十分类似。 class继承也允许子类重写父类继承过来的方法。例如:

<script>
    class Animal{
        constructor(weight,height){
            this.weight = weight;
            this.height = height;
        }
        sleep(){
            console.log('animal is sleeping...');
        }
    }

    class Person extends Animal{
        constructor(name,gender,weight,height){
            super(weight,height);
            this.name = name;
            this.gender = gender;
        }
        sleep(){
            console.log(this.name+"正躺在床上 sleep....");
        }

        thinking(){
            console.log(this.name+" is thinking now!");
        }
    }
    let p = new Person('张三','男',65,170);
    console.log(p);
    p.thinking();
    p.sleep();

</script>
运行结果:
Person {weight: 65, height: 170, name: "张三", gender: "男"}
张三 is thinking now!
张三正躺在床上 sleep....