0
点赞
收藏
分享

微信扫一扫

歌谣学前端之继承

前言

我是歌谣 我有个兄弟 巅峰的时候排名c站总榜19 叫前端小歌谣 曾经我花了三年的时间创作了他 现在我要用五年的时间超越他 今天又是接近兄弟的一天人生难免坎坷 大不了从头再来 歌谣的意志是永恒的 放弃很容易 但是坚持一定很酷 微信公众号前端小歌谣

继承代码案例

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>继承</title>
    <script>

        // 将多个类中的重复代码提取出来
        class Animal{
            constructor(name, age) {
                this.name = name;
                this.age = age;
            }

            sayHello = () => {
                console.log('动物在叫');
            };
        }

        // 通过继承可以使得类中拥有其他类中的属性和方法
        // 使用extends来继承一个类,继承后就相当于将该类的代码复制到了当前类中
        // 当我们使用继承后,被继承的类就称为父类,继承父类的类 称为子类
        class Dog extends Animal{
            /*
            *   子类继承父类后,将获得父类中所有的属性和方法,
            *       也可以创建同名的属性或方法来对父类进行重写
            * */
            sayHello = () => {
                console.log('汪汪汪!');
            };

        }

        class Snake extends Animal{

            // 当在子类中重写父类构造函数时,必须在子类构造函数中第一时间调用父类构造函数,否则会报错
            constructor(name, age, len) {
                super(name, age); // 调用父类构造函数
                this.len = len;
            }

            sayHello = () => {
                console.log('嘶嘶嘶~~');
            };
        }

        const dog = new Dog('旺财', 5);
        const snake = new Snake('长虫', 4, 10);
        // console.log(dog.name, dog.age);
        console.log(snake.name, snake.age, snake.len);

        // dog.sayHello();
        // snake.sayHello();


    </script>
</head>
<body>

</body>
</html>

举报

相关推荐

0 条评论