<html>
<head>
<title>javascript中自定义类2</title>
<script>
//定义Person类
function Person(name,age)
{
this.name = name;//名字
this.age = age;//年龄
//setter方法
this.setName = function (name){
this.name = name;
}
this.setAge = function (age){
this.age = age;
}
//getter方法
this.getName = function (){
return this.name;
}
this.getAge = function(){
return this.age;
}
}
//创建一个对象
var p = new Person();
//没有传入参数,则为undefined
document.write(p.getName() + "," + p.getAge() + "<br/>" );//undefined,undefined
//设置name
p.setName("www");
//设置age
p.setAge(27);
//通过getter方法获取数据
document.write(p.getName() + "," + p.getAge() + "<br/>" );//www,27
//创建另一个对象,使用参数
var p2 = new Person("lisi",25);
document.write(p2.getName() + "," + p2.getAge() + "<br/>" );//lisi,25
</script>
</head>
<body>
</body>
</html>