js继承与众不同
1、为什么需要继承
[js25_1.html]继承示例(冗余)
<html>
<head>
<title>js示例继承示例(冗余)</title>
<script language="javascript"type="text/javascript">
<!--
function MidStu(name,age){
this.name=name;
this.age=age;
this.show=function(){
window.alert(this.name+""+this.age);
}
//计算学费
this.payFee=function(money){
window.alert("应交"+parseFloat(money*0.8));
}
}
function Pupil(name,age){
this.name=name;
this.age=age;
this.show=function(){
window.alert(this.name+""+this.age);
}
//计算学费
this.payFee=function(money){
window.alert("应交"+parseFloat(money*0.5));
}
}
var midStu=new MidStu("顺平",20);
midStu.show();
midStu.payFee(40);
var pupil=new Pupil("sp",30);
pupil.show();
pupil.payFee(40);
//-->
</script>
</head>
<body>
</body>
</html>
//怎么解决代码冗余-->继承
//把学生类抽象出来(即把中学生和小学生的共性拿出来)
[js25_2.html]继承示例(继承优化冗余)
<html>
<head>
<title>js示例继承示例(继承优化冗余)</title>
<script language="javascript"type="text/javascript">
<!--
function Stu(name,age){
this.name=name;
this.age=age;
this.show=function(){
window.alert(this.name+""+this.age);
}
}
function MidStu(name,age){
this.stu=Stu;
this.stu(name,age);//js中实际上通过对象冒充来实现继承(此语句必不可少,因为js是动态语言,如果不执行它,则不能实现继承效果)
//计算学费
this.payFee=function(money){
window.alert("应交"+parseFloat(money*0.8));
}
}
function Pupil(name,age){
this.stu=Stu;
this.stu(name,age);
//计算学费
this.payFee=function(money){
window.alert("应交"+parseFloat(money*0.5));
}
}
var midStu=new MidStu("顺平",20);
midStu.show();
midStu.payFee(40);
var pupil=new Pupil("sp",30);
pupil.show();
pupil.payFee(40);
//-->
</script>
</head>
<body>
</body>
</html>