11JavaScript中通过prototype实现继承
1 <script type="text/javascript"> 2 function Person(name, age, gender) { 3 this.userName = name; 4 this.userAge = age; 5 this.userGender = gender; 6 7 this.sayHello = function () { 8 alert('我叫:' + this.userName + ' 今年:' + this.userAge + '岁了。性别是:' + this.userGender); 9 }; 10 } 11 //为Person的原型中增加一个sayHi 12 Person.prototype.sayHi = function () { 13 alert('Person原型中的SayHi'); 14 }; 15 16 var p = new Person('张三', 10, '男'); 17 18 //Student函数对象(Student构造函数) 19 function Student(name, age,gender) { 20 this.userName = name; 21 this.userAge = age; 22 this.userGender = gender; 23 } 24 25 //设置Student继承自p对象。 26 Student.prototype = p; 27 28 29 Student.prototype.sayByebye = function () { 30 alert('bye bye!!!'); 31 }; 32 33 var s = new Student('李四', 20,'女'); 34 35 s.sayHello(); 36 37 38 39 40 41 </script>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步