js遍歷對象的屬性和方法
一、總結
二、實例
練習1:具有默認值的構造函數
- 實例描述:
有時候在創建對象時候,我們希望某些屬性具有默認值
- 案例思路:
在構造函數中判斷參數值是否為undefined,如果是就為其制定一個默認值。
練習2:遍歷對象屬性和方法
- 實例描述:
通過for...in...語句遍歷對象中的數據,包括屬性和方法
- 案例思路:
for...in語句和if判斷分別遍歷對象的屬性和方法。
三、代碼
1 <!DOCTYPE html> 2 <html lang="zh-cn"> 3 <head> 4 <meta charset="utf-8"> 5 <title>課堂演示</title> 6 </head> 7 <body> 8 <script type="text/javascript"> 9 /* 10 function Hero(type,home,weapon){ 11 this.type=type; 12 this.home=home; 13 // if (weapon==undefined) { 14 // this.weapon='劍'; 15 // }else{ 16 // this.weapon=weapon; 17 // } 18 this.weapon=weapon?weapon:'劍' 19 20 } 21 var user=new Hero('戰士','新手村','斧子') 22 alert(user.type+'\n'+user.home+'\n'+user.weapon) 23 */ 24 25 function Hero(name,type,home,weapon){ 26 this.name=name; 27 this.type=type; 28 this.home=home; 29 this.weapon=weapon?weapon:'劍' ; 30 this.skill=function(){ 31 alert(this.name+'向敵人發動了普通攻擊') 32 } 33 } 34 35 var user=new Hero('阿吉','戰士','新手村') 36 document.write('user包含如下屬性和方法:<hr/>') 37 for (var i in user) { 38 document.write(i+':'+user[i]+'<br/>') 39 } 40 </script> 41 </body> 42 </html>
1、判斷變量是否定義:第13行,判斷一個屬性是否未定義
2、元素屬性默認值的實質(if判斷):第18行,三元運算符實現元素屬性默認值
3、this關鍵字:第26行,函數內元素添加屬性
4、函數內定義方法:第30行
5、for+in遍歷對象:第37行,i就是屬性名或者函數名
6、對象[索引]:第38行,是對應對象索引位置的值,這個索引是屬性名或者函數名
截圖