JavaScript學習之對象

將自定義對象和用內置對象初始化一個變量,使變量成爲對象實踐了一下:

 

不懂將代碼表框,只好這麼寫...

代碼如下:

 

 

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  2.  
  3. <html xmlns="http://www.w3.org/1999/xhtml"> 
  4.  
  5.   
  6.  
  7. <head> 
  8.  
  9. <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> 
  10.  
  11. <title>Learning Object in JavaScript!</title> 
  12.  
  13.   
  14.  
  15. <script type="text/javascript" > 
  16.  
  17. //This function can refill the page with the value of an object 
  18.  
  19. function Show(Object) 
  20.  
  21.  
  22.     for (var ptr in Object){ 
  23.  
  24.         document.write(Object[ptr]); 
  25.  
  26.         document.write("<br/>"); 
  27.  
  28.         } 
  29.  
  30.   
  31.  
  32.  
  33.   
  34.  
  35. //Define an object "People" 
  36.  
  37.     function Peoples(name,age) 
  38.  
  39.     { 
  40.  
  41.         this.name=name; 
  42.  
  43.         this.age=age; 
  44.  
  45.     } 
  46.  
  47. </script> 
  48.  
  49. </head> 
  50.  
  51.   
  52.  
  53. <body> 
  54.  
  55. <script type="text/javascript" > 
  56.  
  57.     //Create a new Object with Object 
  58.  
  59.     var p=new Object(); 
  60.  
  61.     p.name="Baby Aloha"
  62.  
  63.     p.age=20
  64.  
  65.      
  66.  
  67.     //Go through the Object 
  68.  
  69.     for (var prop in p) 
  70.  
  71.         alert(p[prop]); 
  72.  
  73.   
  74.  
  75.   
  76.  
  77.     //Create a object with the object 
  78.  
  79.     var q=new Peoples(); 
  80.  
  81.     q.name="Andrew"
  82.  
  83.     q.age=19
  84.  
  85. </script> 
  86.  
  87.   
  88.  
  89. <input type="button" value="Show Props!" onclick="Show(q);"/> 
  90.  
  91. <p>Click the button to show information I`ve set to variable q.</p> 
  92.  
  93. </body> 
  94.  
  95.   
  96.  
  97. </html> 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章