1、直接创建对象
<script type="text/javascript">
person=new Object();
person.name="Joe";
person.age=39;
person.weight=70;
document.write(person.name+" is "+person.age+" years old!");
</script>
或者:
<script type="text/javascript">
var person={
name:"Joe",
age:39,
weight:70,
}
document.write(person.name+" is "+person.age+" years old!"+"<br/>");
</script>
2、对象构造器
即通过函数来创建对象(类似于C++中的构造函数的思想)
<script type="text/javascript">
function person(name,age,weight){
this.name=name;
this.age=age;
this.weight=weight;
}
myfather=new person("Joe",39,70);
document.write(myfather.name+" is "+myfather.age+" years old !");
</script>
利用对象构造器就让我们的代码复用性更强,代码利用率更高。因为我可以用不同的身份调用,创建不同的对象
如:
<script type="text/javascript">
person=new Object();
person.name="Joe";
person.age=39;
person.weight=70;
document.write(person.name+" is "+person.age+" years old!"+"<br/>");
</script>
<script type="text/javascript">
function person(name,age,weight){
this.name=name;
this.age=age;
this.weight=weight;
}
myfather=new person("Joe",39,70);
document.write(myfather.name+" is "+myfather.age+" years old !"+"<br/>");
mystudent1=new person("Jackson",4,20);
document.write(mystudent1.name+" is "+mystudent1.age+" years old !"+"<br/>");
</script>
则浏览器输出