<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script type="text/javascript">
var o={
say:function()
{
if (this.name && this.age && this.sex)
{
alert('名字叫:'+this.name+',今年:'+this.age+'岁了,是个'+this.sex+'的');
}
else
{
alert('参数不完整');
}
},
getName:function() //仿C#属性
{
if (this.name) return this.name;
},
setName:function(name)
{
if (name){
this.name=name;
}
},
getAge:function()
{
if (this.age) return this.age;
},
setAge:function(age)
{
if (age)
{
this.age=age;
}
},
setSex:function(sex)
{
if (sex){
this.sex=sex;
}
},
getSex:function()
{
if (this.sex) return sex;
}
};
var Person=function(name,age,sex) //构造函数
{
this.name=name;
this.age=age;
this.sex=sex;
};
Person.prototype=o; //原型链接
var p1 = new Person("john",18,'男');
var inherited=function(add)
{
if (add) {
this.add=add;
}
var old=this.say;
this.say=function() //模拟C#重写函数
{
old.apply(this,[]);
if (this.add) {
alert('地址在'+this.add);
}
}
}
p1.say(); //继承前
inherited.call(p1,"XX中街XX号"); //继承p1,增加一个地址
p1.say();
</script>
</head>
<body>
</body>
</html>
javascript模拟C#继承练习
最新推荐文章于 2024-06-02 16:57:39 发布