123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- <!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>
- function Person(userName, userAge) {
- this.userName = userName;
- this.userAge = userAge;
- // this.talk = function () {
- // console.log(`大家好我叫${this.userName}今年${this.userAge}岁了`);
- // }
- }
- Person.prototype.loveCoding = "四福";
- Person.prototype.talk = function () {
- console.log(`大家好我叫${this.userName}今年${this.userAge}岁了`);
- }
- // var p1 = new Person('张三', 18);
- // p1.talk();
- // 构造继承 无法继承原型上的属性和方法
- // function Student(userName,userAge,school) {
- // Person.call(this,userName,userAge);
- // this.school = school;
- // }
- // let s1 = new Student('张三',18,'清华大学');
- // console.log(s1.userName);
- // console.log(s1.loveCoding);
-
- // 原型继承 无法继承构造函数中的属性和方法
- // function Student(userName,userAge,school) {
- // // this.userName = userName;
- // // this.userAge = userAge;
- // this.school = school;
- // }
- // Student.prototype = new Person();
- // let s1 = new Student('张三',18,'清华大学');
- // console.log(s1.loveCoding);
- // console.log(s1.userName);
- // s1.talk();
- // 组合继承
- function Student(userName,userAge,school) {
- // 构造函数继承 可以继承到构造函数中的属性和方法
- Person.call(this,userName,userAge);
- this.school = school;
- }
- // 原型继承 可以继承到原型上的属性和方法
- Student.prototype = new Person();
- // 修复构造函数指向问题
- Student.prototype.constructor = Student;
- let s1 = new Student('张三',18,'清华大学');
- console.log(s1.loveCoding);
- console.log(s1.userName);
- console.log(s1.constructor);
- </script>
- </body>
- </html>
|