推荐的构造函数定义方式

推荐的构造函数定义方式

 1 <script>
 2         //定义一个Animal类
 3         function Animal (name) {
 4             // 公有属性
 5             //把属性放在构造函数里是为了方便从构造函数中接收参数
 6             this.name = name || "prince";
 7             this.type = "animal";
 8             //约定私有属性
 9             //为了方便给原型中的方法调用
10             this._age = 20;
11         }
12         //修改Animal类的原型
13         Animal.prototype = {
14             //以_开头为私有方法
15             //用来给原型中其他方法调用,不对外调用
16             _move : function (){
17                 //alert("");
18             },
19             //公有方法
20             say : function (){
21                 //alert();
22             },
23             act : function (){
24                 this._move();
25             }
26         }
27         //实例化Animal对象
28         var myDog = new Animal("dada");
29         myDog.say();
30         myDog.act();
31         myDog._move();//不推荐
32         alert(myDog._age);//不推荐
33     </script>

 

posted @ 2013-11-11 18:41  snowinmay  阅读(336)  评论(1编辑  收藏  举报