创建你自己的对象
有多种不同的办法来创建对象:
1. 创建对象的实例
下列代码创建了一个对象的实例,并向其添加了四个属性:
personObj=new Object()
personObj.firstname="John"
personObj.lastname="Doe"
personObj.age=50
personObj.eyecolor="blue"
向 personObj 添加方法也很简单。下列代码向 personObj 添加了名为 eat() 的方法:
2. 创建对象的模版
模版定义了对象的结构。
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname
this.lastname=lastname
this.age=age
this.eyecolor=eyecolor
}
注意:模版仅仅是一个函数。你需要在函数内部向 this.propertiName 分配内容。
一旦拥有模版,你就可以创建新的实例,就像这样:
myFather=new person("John","Doe",50,"blue")
myMother=new person("Sally","Rally",48,"green")
同样可以向 person 对象添加某些方法。并且同样需要在模版内进行操作:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname
this.lastname=lastname
this.age=age
this.eyecolor=eyecolor
this.newlastname=newlastname
}
注意:方法只是依附于对象的函数而已。然后,我们需要编写 newlastname() 函数:
function newlastname(new_lastname)
{
this.lastname=new_lastname
}
实例1:
<html>
<body>
<script type="text/javascript">
personObj=new Object()
personObj.firstname="John"
personObj.lastname="Adams"
personObj.age=35
personObj.eyecolor="black"
alert(personObj.firstname + " 的年龄是 " + personObj.age + " 岁。")
</script>
</body>
</html>
实例2:
<html>
<body>
<script type="text/javascript">
function person(name,age,sex)
{
this.name=name;
this.age=age;
this.sex=sex;
this.setName=newName;
/**修改用户姓名*/
function newName(newName)
{
newName='李鹏';
this.name=newName;
}
}
myFather=new person("John",35,"男")
alert("初始姓名:"+myFather.name);
myFather.setName('aa');
alert("修改后的姓名:"+myFather.name);
</script>
</body>
</html>