给对象添加普通函数和对象属性的遍历

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         <script type="text/javascript">
 7             
 8             function user(name,age,sex){
 9                 this.name = name;
10                 this.age = age;
11                 this.sex = sex;
12                 this.show = function (){  //给对象添加函数,这里弄的匿名函数
13                     console.log(this.name+" "+this.age+" "+this.sex);
14                 }
15                 this.setAge = function(age){
16                     this.age = age;
17                 }
18             }
19             
20             user1 = new user("凡涛",20,"")  //直接在这里赋值
21             user1.show();   //调用show方法
22             user1.setAge(18);
23             user1.show();
24             
25             user1.setSchool = function(school){   //还可随时添加新的函数
26                 this.school = school;
27                 console.log(this.school);
28             }
29             
30             user1.setSchool("What school?");
31             
32             console.log(user1.name);  //访问对象里属性的两种方法
33             console.log(user1["name"]);  //通过键来访问
34             
35             for(key in user1) //key是自己定义的,in表示在user1里面遍历
36             {
37                 console.log(key+":"+user1[key]); //也是通过键访问值
38             }
39         </script>
40     </head>
41     <body>
42     </body>
43 </html>

 注意,对象里面的属性不是只能在构造函数里面设置,由于JS这语言比较随意,也可以在外面继续添加,想怎么加就怎么加。

posted @ 2021-02-09 17:33  EvanTheBoy  阅读(139)  评论(0)    收藏  举报