1 <script type="text/javascript">
2 //JavaScript创建对象
3
4 //只在局部起作用
5 function createTheObject1()
6 {
7 var person = new Object();
8 person.name = "wyf";
9 person.sex = "1";
10 person.age = 18;
11
12 document.write("name:"+person.name+", sex: "+person.sex+", age: "+person.age);
13 };
14
15
16
17 //由一对大括号括起来
18 function createTheObject2(){
19 var myObj =
20 {
21 "id": 5,
22 "fun1": function()
23 {
24 document.writeln(this.id+', '+this.name);//以对象的形式访问
25 },
26 "name": "myObj",
27 "fun2": function()
28 {
29 document.writeln(this['id']+ '+' + this['name']);//以集合的形式访问
30 }
31 };
32
33 myObj.fun1();
34 myObj.fun2();
35 }
36
37 //用 function 关键字模拟 class
38 function myClass()
39 {
40 this.id = 5;
41 this.name = 'wyf';
42 this.getName = function()
43 {
44 return this.name;
45 };
46 this.getId = function()
47 {
48 return this.id;
49 }
50 }
51
52 function createTheObject3()
53 {
54 var my = new myClass();
55 alert(my.getId()+ '+' + my.getName());
56 }
57
58 //在函数体中创建一个对象,声明其属性再返回
59 function myClass3()
60 {
61 var myObj =
62 {
63 'id': 1,
64 'name': 'wyf'
65 }
66
67 return myObj;
68 }
69
70 function myClass4()
71 {
72 var myObj = new Object();
73 myObj.id = 1;
74 myObj.name = 'wyf';
75
76 return myObj;
77 }
78
79
80 </script>