OOP in Javascript(3)

本文介绍两种JavaScript中的继承实现:一种是通过原型链实现方法的继承,另一种是通过构造函数调用实现属性继承。同时展示了如何使用这两种方法创建继承关系,并演示了如何重写父类的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
  • Inheritance in Javascript
  1.   <script language="javascript" type="text/javascript">
  2.     <!-- 
  3.         function SuperClass(){
  4.             //attach method supperTest
  5.             this.superTest=superTest;
  6.         }
  7.         
  8.         function subClass(){
  9.             this.inheritFrom = SuperClass;
  10.             this.inheritFrom();
  11.             this.subTest=subTest;// subTest
  12.         }
  13.         
  14.         
  15.         function superTest() {
  16.           return "superTest";
  17.         }
  18.           
  19.         function subTest() {
  20.           return "subTest";
  21.         }
  22.         
  23.         //use example
  24.         var obj =new subClass();
  25.         alert(obj.subTest());
  26.         alert(obj.superTest());
  27.         
  28.         
  29.         //another way of inheritance
  30.         
  31.         Person=function(name)
  32.         {   
  33.             this.name=name
  34.         };
  35.         Person.prototype={
  36.             Speak:function(msg){
  37.                 alert(this.name + ":" + msg);
  38.             },
  39.             Walk:function(){
  40.                 alert(this.name + ":" + "walk");
  41.             }
  42.         };
  43.         
  44.         //test person
  45.         var p=new Person("person");
  46.         p.Speak("GC");
  47.         p.Walk();
  48.         
  49.         
  50.         
  51.         //student derive from class person
  52.         Student =function(){
  53.         };
  54.         //inherit from Person
  55.         Student.prototype=new Person();
  56.         //add methods
  57.         Student.prototype.Study=function(){
  58.             alert("Benny studies!");
  59.         }
  60.         
  61.         //test student
  62.         var s=new Student();
  63.         s.name="benny.s.xu";
  64.         s.Walk();
  65.         s.Speak("newegg");
  66.         
  67.         //override speak method
  68.         Student.prototype.Speak=function(){
  69.             alert("override speak method");
  70.         } 
  71.         s.Speak();
  72.         
  73.     -->
  74.     </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值