老师寄生组合式少用了一次超类函数,但是又多写了一个函数啊
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> // 寄生组合式继承 比 组合继承(组合继承调用了两次超类函数) 好一点?? // 函数接收两个参数 subType子类的构造函数 superType父类的构造函数 function inheritPrototype(subType,surperType) { var prototype=Object.create(surperType.prototype); subType.prototype=prototype; } // surperType function People(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } People.prototype.sayHello = function () { console.log('你好我是' + this.name + '我的年龄是' + this.age + '我是' + this.sex + '生'); }; People.prototype.sleep = function () { console.log(this.name + 'zzzz'); }; // subType function Student(name, age, sex, school, studentNumber) { People.call(this,name, age, sex); this.school = school; this.studentNumber = studentNumber; } // 实现继承 inheritPrototype(Student,People); //老师这里要实现继承也要调用一次函数啊 Student.prototype.study = function () { console.log(this.name + '学习了'); } Student.prototype.exam = function () { console.log(this.name + '考试了'); } Student.prototype.sayHello = function () { console.log(this.name + '敬礼'); } // Student的实例 var xiaogang = new Student('小刚', 12, '男', '艾利斯顿商学院', 10086); console.log(xiaogang.name); console.log(xiaogang.school); xiaogang.sayHello(); xiaogang.exam() // Peopel实例 var laozhao = new People('张继你', 55, '男'); laozhao.sayHello(); </script> </body> </html>
下面是第二个问题:讲了这么多种继承,是不是最初的利用原型链实现继承最省内存呢? 初了子类属性代码看起来没那么简洁之外。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> // 利用原型链实现继承 子类拥有符类的所有属性和方法 function People(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } People.prototype.sayHello= function () { console.log('你好我是' + this.name + '我的年龄是' + this.age + '我是' + this.sex + '生'); }; People.prototype.sleep= function () { console.log(this.name + 'zzzz'); }; // 子类也要被定义 function Student(name, age, sex,school,studentNumber) { this.name = name; this.age = age; this.sex = sex; this.school=school; this.studentNumber=studentNumber; } // ***实现继承的关键语句!!!! Student.prototype=new People(); Student.prototype.study=function() { console.log(this.name+'学习了'); } Student.prototype.exam=function() { console.log(this.name+'考试了'); } // 子类可以重写父类的方法 Student.prototype.sayHello=function() { console.log(this.name+'敬礼'); } // Student的实例 var xiaogang=new Student('小刚',12,'男','艾利斯顿商学院',10086); console.log(xiaogang.name); console.log(xiaogang.school); xiaogang.sayHello(); xiaogang.exam(); // Peopel实例 var laozhao=new People('张继你',55,'男'); laozhao.sayHello(); </script> </body> </html>
源自:面向对象
8-8 寄生组合式继承
25
收起
正在回答 回答被采纳积分+1
1回答
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星