代码改变世界

Javascript 原型简单练习

2012-01-05 16:39  音乐让我说  阅读(335)  评论(0编辑  收藏  举报

直接贴代码了:

<!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>Javascript 原型练习</title>
<script type="text/javascript">
function Test1()
{
var Student = function(name,age)
{
this.Name = name;
this.Age = age;
};
Student.prototype.Show
= function()
{
alert(
"你好,我叫 "+ this.Name +",今年 "+ this.Age +" 岁。");
}
var stu = new Student("赵云",18);
stu.Show();
// 你好,我叫 赵云,今年 18 岁。

var Teacher = function(name)
{
this.Name = name;
};
Teacher.prototype.Students
= [];
var teacher = new Teacher("吴老师");
alert(
"目前,"+ teacher.Name +" 拥有的学生数:" + teacher.Students.length);

teacher.Students.push(
new Student("关羽",19));
teacher.Students.push(
new Student("张飞",20));
teacher.Students.push(
new Student("诸葛亮",21));

alert(
"目前,"+ teacher.Name +" 拥有的学生数:" + teacher.Students.length);

alert(
"下面准备遍历 " + teacher.Name + "的学生!");
for(var i = 0, len = teacher.Students.length; i < len; i++) // 也可以用 for(var i in teacher.Students) ,这里的 i 为索引
{
var stuItem = teacher.Students[i];
stuItem.Show();
}
alert(
"遍历结束");
}
function Test2()
{
var Person = function(name,age)
{
this.Name = name;
this.Age = age;
};
Person.prototype.Show
= function()
{
if(this.Age != undefined)
{
alert(
"你好,我叫 "+ this.Name +",今年 "+ this.Age +" 岁。");
}
else
{
alert(
"你好,我叫 "+ this.Name +",年龄我不告诉你!");
}
}
var person1 = new Person();
person1.Show();
var person2 = new Person("周杰伦");
person2.Show();
var person3 = new Person("林俊杰",30);
person3.Show();

var Student = function(grade)
{
this.Grade = grade;
};
Student.prototype
= new Person("潘玮柏",32);

var stu1 = new Student("六年级");
stu1.Show();
alert(
"姓名:" + stu1.Name + "\n" + "年龄:" + stu1.Age + "\n" + "年级:" + stu1.Grade);
}
window.onload
= function()
{
document.getElementById(
"btn1").onclick = Test1;
document.getElementById(
"btn2").onclick = Test2;
};
</script>
</head>
<body>
<div>
<h1>Hello World</h1>
</div>
<div style="margin:30px 0px;">
<input type="button" value="示例1 - 练习基本的 Prototype 使用" id="btn1"/>
<input type="button" value="示例2 - 进阶" id="btn2"/>
</div>

</body>
</html>

 

谢谢浏览!