还剩1页未读,继续阅读
文本内容:
实训案例名称理解面向对象特性JavaScript.任务介绍1定义一个类作为类的子类,在类中继承父类的方法、重新定义父类的Student Person Student walksayHello方法并添加类自己的方法Student sayGoodBye.任务目标2理解面向对象的四大特性并掌握创建对象的方法JavaScript实现思路
3.选用构造函数模式创建对象,并且将属性为方法的属性定义到函数之外1全局变量是绑定在对象上的,是对象的属性2window window实现代码
4.完整代码如脚本所示4-5脚本4-
5.htmlhtml〈面向对象特性vhead titleJavaScriptv/titlev/headscriptfunction PersonfirstName{this.firstName=firstName;Person.prototype.walk=function{console.Iogl amwalking!*;Person.prototype.sayHello=function{console.logfHello,Tm+this.firstName;function StudentfirstName,subject{Person.callthis,firstName;this.subject=subject;Student.prototype=Object.createPerson.prototype;Student.prototype.constructor=Student;Student.prototype.sayHello=function{console.logHello,Im+this.firstName+Tm studying+this.subject+Student.prototype.sayGoodBye=function{;console.logGoodbye!nvar studentl=new Studen^Uanet*,Applied Physics;student
1.sayHello;studentl,walk;studentl.sayGoodBye;console.Iogstudent1instanceof Person;console.Iogstudent1instanceof Student;/script/html分析如下1function PersonfirstName{this.firstName=firstName;首先定义父类构造函数Person2Person.prototype.walk=function{console.IogI amwalking!;通过父类添加方法Person.prototype walko3Person.prototype.sayHello=function{console.logHello,Im+this.firstName;通过父类添加方法Person.prototype sayHelloo二4function StudentfirstName,subject{Person.callthis,firstName;this.subject subject;定义子类构造函数,在函数内部通过方法调用父类构造器,最后初始化类特有属Student callStudent性subjecto二5Student.prototype Object.createPerson.prototype;通过方法来实现继承将父类继承给对象Object.create Person.prototype Student.prototype6Student.prototype.constructor=Student;设置的属性指向Student.prototype^constructor Student7Student.prototype.sayHello=function{console.logHello,Em+this.firstName+Im studying+this.subject+在子类中重写父类的方法sayHello8Student.prototype.sayGoodBye=function{console.logGoodbye!;在子类中增加自己独有的方法sayGoodBye9var student1=new StudentJanet,nApplied Physics1;studentl.sayHello;student
1.walk;studentl.sayGoodBye;实例化子类并调用子类的、和方法会打印出子类的sayHello walksayGoodBye studentl.sayHello sayHello方法,这里子类对父类的方法实现了重写会调用父类的方法,这里子类对父类sayHeHo;studentl.walk;walk的实现了继承walk10console.logstudent1instanceof Person;console.logstudent1instanceof Student;通过操作符验证既是父类的实例也是子类的实例instanceof studentlPersonStudent运行结果
5.运行结果如图所示
4.5Developer Tools-file:///G:/ziliao/JavaScript%E7%A8%3B%E
5...—□XG[5ZI ElementsConsole SourcesNetwork TimelineProfiles»0q top▼U Preservelog脚本Hello,Im Janet.I*m studyingApplied Physics.4-
5.html:21脚本I amwalking!4-
5.httnl:8脚本Goodbye!4-
5.html:24true映本4・
5.html:32蒯本true4-
5.html:33图任务运行结果
4.54-2。
个人认证
优秀文档
获得点赞 0