07物件的建立

白茶花约發表於2024-03-14
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <title>Document</title>
 7 
 8     <script>
 9         /*
10             建立物件的語法:    
11                 1 new Object()
12                 2 {屬性名:屬性值, ... ..., 函式名:function(){}}
13         */
14 
15         var person = new Object()
16         //新增屬性
17         person.name = '張三'
18         person.age = 10
19         //新增方法
20         person.eat = function(food){document.write(this.age+"歲的"+this.name+"正在吃"+food)}
21         //訪問屬性
22         console.log(person.name)
23         console.log(person.age)
24         //呼叫方法
25         person.eat("火鍋")
26 
27         document.write("<hr>")
28         
29         var person = {
30             "name":"李四",
31             "age":20,
32             "eat":function(food){
33                 document.write(this.age+"歲的"+this.name+"正在吃"+food)
34             }
35         }
36         person.eat("烤肉")
37 
38     </script>
39 
40 </head>
41 <body>
42     
43 </body>
44 </html>

相關文章