Javascript创建对象的学习和使用

时间:2023-03-08 23:52:05
Javascript创建对象的学习和使用
 <html>
<head>
<meta charset="utf-8">
<title>javascript对象的学习</title>
</head>
<body>
<h1>1.使用JS创建person对象,里面有id,name,age,sex属性 ,有eat,run方法 (2种方法创建)</h1><hr>
<script language="javascript">
document.write("<h2>"+"第一种方法"+"</h2>");
var person=new Object();
person.id="10010";
person.name="小别";
person.age=22;
person.sex="男";
person.eat=function(){
document.write("eat()方法:男的喜欢吃高热量的食物!");
}
person.run=function(){
document.write("run()方法:程序员要自觉锻炼身体哟!");
}
document.write("编号:"+person.id+"<br/>");
document.write("姓名:"+person.name+"<br/>");
document.write("年龄:"+person.age+"<br/>");
document.write("性别:"+person.sex+"<br/>");
person.eat();
document.write("<br/>");
person.run();
document.write("<br/>");
document.write("<h2>"+"第二种方法"+"</h2>");
var person=new Person("10011","小李",23,"男");
function Person(id,name,age,sex){
this.id=id;
this.name=name;
this.age=age;
this.sex=sex;
this.eat=function(){
document.write("eat()方法:女的应该吃低热量的食物哟!");
}
this.run=function(){
document.write("run()方法:女程序员也要自觉锻炼身体哟!");
}
}
document.write("编号:"+person.id+"<br/>");
document.write("姓名:"+person.name+"<br/>");
document.write("年龄:"+person.age+"<br/>");
document.write("性别:"+person.sex+"<br/>");
person.eat();
document.write("<br/>");
person.run();
document.write("<br/>");
document.write("<h2>"+"第三种:创建对象使用最多的方法"+"</h2>");
var person={id:"10012",name:"小赵",age:24,sex:"男",eat:function(){
document.write("eat():男的女的都喜欢吃好的");
},run:function(){
document.write("run():男的女的都懒哟!所以要自觉!");
}};
document.write("编号:"+person.id+"<br/>");
document.write("姓名:"+person.name+"<br/>");
document.write("年龄:"+person.age+"<br/>");
document.write("性别:"+person.sex+"<br/>");
person.eat();
document.write("<br/>");
person.run();
document.write("<br/>");
</script> </body>
</html>

Javascript创建对象的学习和使用