| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <!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>
- // 构造函数 比如 Array、Object、Function、String、Number、Boolean、Date 等
- // console.log(Array);
- // 也可以自定构造函数
- function Person(userName,age) {
- this.userName = userName;
- this.age = age;
- }
- // 为构造函数添加方法
- Person.prototype.sayName = function(){
- // console.log("我是"+this.userName+",我今年"+this.age+"岁");
- console.log(`我是${this.userName},我今年${this.age}岁`);
-
- }
- // 调用构造函数
- // var p1 = new Person("张三",18);
- // // console.log(p1.userName,p1.age);
- // // 调用方法
- // p1.sayName();
- // var p2 = new Person("李四",20);
- // p2.sayName();
- // 用继承的方式生成一个新的构造函数
- function Student(userName,age,school) {
- // 调用父类的构造函数 继承父类的属性
- Person.call(this,userName,age);
- this.school = school;
- }
- //继承父类的方法
- Student.prototype = new Person();
- // 为子类添加方法
- Student.prototype.saySchool = function(){
- console.log(`我来自${this.school}`);
-
- }
- // 调用子类的构造函数
- var s1 = new Student("王五",22,"清华大学");
- console.log(s1.userName,s1.age);
- // 调用方法
- s1.sayName();
- s1.saySchool();
- // ES中没有类,只有构造函数和原型 模拟类
-
- </script>
- </body>
- </html>
|