javascript疑难问题---1、ES6继承小实例

javascript疑难问题---1、ES6继承小实例

一、总结

一句话总结:

js中的类和继承可以多用es6里面的,和其它后端语言的使用方法一样
    class Animal {
        constructor(name) {
            this.name = name;
        }
        say() {
            console.log('我是'+this.name);
        }
    }
    class Bird extends Animal {
        constructor(name, age) {
            super(name);
            this.age = age;
        }
        fly() {
            console.log('我是'+this.name+','+this.age+'岁,我在自由自在的飞翔!');
        }
    }
    let animal1=new Animal('大动物');
    animal1.say();
    let monkey=new Bird('飞猴',15);
    monkey.fly();

1、es6类使用?

class Animal,然后构造函数 constructor(name)
    class Animal {
        constructor(name) {
            this.name = name;
        }
        say() {
            console.log('我是'+this.name);
        }
    }
    let animal1=new Animal('大动物');
    animal1.say();

2、es6继承使用?

class Bird extends Animal,并且构造函数constructor(name, age)里面是 super(name);
    class Bird extends Animal {
        constructor(name, age) {
            super(name);
            this.age = age;
        }
        fly() {
            console.log('我是'+this.name+','+this.age+'岁,我在自由自在的飞翔!');
        }
    }

二、ES6继承小实例

博客对应视频位置:1、es6继承小实例
https://fanrenyi.com/video/4/20

1、需求

创建Animal类(name属性,say方法)
创建Animal类的子类Bird类(age属性,fly方法)

2、效果及实例

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <script>
 9     class Animal {
10         constructor(name) {
11             this.name = name;
12         }
13         say() {
14             console.log('我是'+this.name);
15         }
16     }
17     class Bird extends Animal {
18         constructor(name, age) {
19             super(name);
20             this.age = age;
21         }
22         fly() {
23             console.log('我是'+this.name+','+this.age+'岁,我在自由自在的飞翔!');
24         }
25     }
26     let animal1=new Animal('大动物');
27     animal1.say();
28     let monkey=new Bird('飞猴',15);
29     monkey.fly();
30 </script>
31 </body>
32 </html>
 
原文地址:https://www.cnblogs.com/Renyi-Fan/p/12030093.html