学JS面向对象 以及里面的继承

看看JS的面向对象,然后写了个例子

 

定义一个类:人, 人有名字的属性,人有说出名字的函数

var Person = function (name) {
this.name = name;
};

Person.prototype = {
"name": name,
"sayname": function () {
alert("我的名字:"+this.name);
}
};

再定义一个学生类,学生继承自人,并且有学号,和说出学号 的方法

var Student = function (name, number) {
this.name = name;
this.number = number;
};

Student.prototype = Inherit(new Person(this.name),
{
"number": this.number,
"saynumber": function () {
alert("我的学号:"+this.number);
}
}
);

为了让学生继承人的所有属性和方法,自定义一个继承操作函数

/**继承时接受父类的属性和函数*/
function Inherit(parent,son){
for(var pro in parent){
son[pro] = parent[pro];
}
return son;
}

测试页面html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/Student.js" type="text/javascript"></script>
<script type="text/javascript">
var stu = new Student("张三", 2008);
stu.sayname();
stu.saynumber();

</script>
</head>
<body>

</body>
</html>

 

 




 

posted @ 2011-12-22 16:49  如坐夕阳  Views(192)  Comments(0Edit  收藏  举报