研究javascript的几个例子(一)

本文介绍了一个使用JavaScript实现构造函数继承的例子。通过BaseClass和SonClass两个类展示了如何在子类中继承父类的方法和属性,并对原型链上的属性进行覆盖及扩展。
关键字:构造继承,prototype
JS.js文件:
function BaseClass(){
    
this.name="BaseClass";
    
//this.prototype.Height="1.5米"; 错误写法
    BaseClass.prototype.Height="1.5米";
    
this.Width="2米";
    
this.Weight="1吨";
    
this.say=function(){
     
return "my name is "+this.name+",Height:"+this.Height+",Width:"+this.Width+",Weight:"+this.Weight;
    }

}

function SonClass(){
    
this.base=BaseClass;
    
this.base();
    
this.Weight="2吨";
    
this.Color="red";
    
this.Title="SonClass";
    
this.loudsay=function(){
       
return "my name is "+this.Title+",Height:"+this.Height+",Width:"+this.Width+",Weight:"+this.Weight+",Color:"+this.Color;
    }

}

    SonClass.prototype.Speed
="100";
    SonClass.prototype.run
=function(){
        
return "my name is "+this.Title+",Height:"+this.Height+",Width:"+this.Width+",Weight:"+this.Weight+",Color:"+this.Color+",Speed:"+this.Speed;
}


HTML:
<html>
    
<head>
        
<title></title>
          
<script src=jS.js type="text/javascript"></script>
          
<script language=javascript>
              
//BaseClass baseclass = new BaseClass();错误写法
              var baseclass = new BaseClass();
              alert(baseclass.name);    
//Base       
              alert(baseclass.say());//my name is BaseClass,Height:1.5米,Width:2米,Weight:1吨
              var Son = new SonClass();
              alert(Son.say());
//my name is BaseClass,Height:undefined,Width:2米,Weight:2吨
              alert(Son.loudsay());//my name is SonClass,Height:undefined,Width:2米,Weight:2吨,Color:red
              alert(Son.run());//my name is SonClass,Height:undefined,Width:2米,Weight:2吨,Color:red,Speed:100
              SonClass.prototype.Height="2.5米";
              alert(Son.run());
//my name is SonClass,Height:2.5米,Width:2米,Weight:2吨,Color:red,Speed:100
         
</script>
    
</head>
    
<body >
    
    
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值