使用javascript创建类的方式:
一:创建object对象,扩展它
var stu = new Object();
stu.id=1;
stu.name="shizhan";
stu.age=22;
stu.setName=function(name)
{
this.name = name;
}
stu.getName=function()
{
return this.name;
}
二:使用对象字面值
var stu ={
name:"eeee",
age:2033,
id:232,
setName:function(name)
{
this.name=name;
},
getName:function()
{
return this.name;
}
}
三:定义构造函数创建我们自己的类
Student.num =0; //类的静态变量
function Student(id,name,age)
{
this.name = name;
this.id = id;
this.age = age;
Student.num++;
}
四:with关键字,有了with关键字后,我们可以不必为每个属性加上this,可以用with(this)
{
}代替所有的this。
Student.num =0;
function Student(id,name,age)
{
this.name = name;
this.id = id;
this.age = age;
this.show =show;
Student.num++;
}
function show()
{
with(this)
{
var info="姓名";
info=info+name+"年龄: "+age+" id: "+id;
return info;
}
}
五:使用for in 遍历类的属性
var str="";
//遍历的是所有的属性,一个一个取值
for(var pro in stu)
{
//使用的是属性值=对象名[属性名]
str=str+pro+":"+stu[pro]+"</br>";
}
六:使用原型扩展类的属性,如果我们只是 对象.属性名(这个属性之前不存在),那么只是当前这个对象增加了这个属性,但是其他 属于这个类的对象,并不拥有这个属性。因此我们可以使用类名.prototype.属性来为类增加新的属性,下面是示例。
<script type="text/javascript">
function Student(id,name)
{
this.name = name;
this.id = id;
}
var a = new Student(1,"aaa");
var b = new Student(2,"bbbb");
//使用原型为类增加属性
//Student.prototype.age=20;
//如果使用的是下面的方式b的age将是undefined
a.age=15;
document.write(a.name+" "+a.id+" "+a.age+"</br>");
document.write(b.name+" "+b.id+" "+b.age);
</script>
测试代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
/* 第一种创建类的方式
var stu = new Object();
stu.id=1;
stu.name="shizhan";
stu.age=22;
stu.setName=function(name)
{
this.name = name;
}
stu.getName=function()
{
return this.name;
}
stu.setName("heihei");
//第二种创建类的方式
//创建静态变量
Student.num =0;
function Student(id,name,age)
{
this.name = name;
this.id = id;
this.age = age;
Student.num++;
}
var stu = new Student(23,"shizhan",22);
var stu = new Student(22,"xxx",22);
var stu = new Student(21,"seee",22);*/
var stu ={
name:"eeee",
age:2033,
id:232,
setName:function(name)
{
this.name=name;
},
getName:function()
{
return this.name;
}
}
</script>
</head>
<body>
<script type="text/javascript">
var str="";
for(var pro in stu)
{
str=str+pro+":"+stu[pro]+"</br>";
}
document.write(str);
//document.write("学生的个数有:"+Student.num);
</script>
</body>
</html>