您的位置:首页 > Web前端 > JavaScript

javascript模拟C#继承练习

2016-05-29 16:05 417 查看
<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: