天天看點

多種方式建立JavaScript對象

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>      

繼續閱讀