| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <script>
- // 类的定义 (ES6)使用class关键字
- class Person{
- //constructor 构造函数 用于初始化对象的属性
- constructor(userName,age){
- this.userName = userName;
- this.age = age;
- }
- // 为类添加方法
- sayName(){
- console.log(`我是${this.userName},今年${this.age}岁`);
- }
- }
- // 调用类的构造函数
- // let p1 = new Person("张三",20);
- // console.log(p1.userName,p1.age);
- // // 调用方法
- // p1.sayName();
- // 类的继承 (ES6)使用extends关键字
- class Student extends Person{
- constructor(userName,age,school){
- // 调用父类的构造函数 继承父类的属性
- super(userName,age);
- this.school = school;
- }
- // 为子类添加方法
- saySchool(){
- console.log(`我是${this.userName},我来自${this.school}`);
- }
- }
- // 调用子类的构造函数
- let s1 = new Student("李四",18,"清华大学");
- console.log(s1.userName,s1.age,s1.school);
- // 调用方法
- s1.sayName();
- s1.saySchool();
-
- </script>
- </body>
- </html>
|