javascript-面向对象和原型(2).

继续....先来一段 常见构造函数

1 function Box(){};                                                     
2         Box.prototype.name='Lee';
3         Box.prototype.age=100;
4         Box.prototype.run=function()
5         {
6                 return this.name + this.age+'运行中...';
7         };
8         
9         var box1 = new Box();

★访问构造函数原型

1 function Box(){};                                                     
2         
3         var box1 = new Box();
4         //alert(box.prototype);                //使用对象实例无法访问到prototype
5         //alert(box._proto_);                 //使用对象实例访问prototype的指针
6         alert(Box.prototype);                //使用构造函数名(对象名)访问prototype

★使用字面量的方式创建原型对象

 1 /*在使用字面量创建原型对象的时候,字面量创建的方式使用constructor属性不会指向实例
 2    so,我们可以在原型字面量里面添加constructor强至指向 指定的构造函数
 3 */
 4 function Box(){}
 5 Box.prototype={
 6     constructor:Box;       //
 7     
 8     name:'Lee',
 9     age:100,
10     run:function()
11         {
12                 return this.name + this.age+'运行中...';
13         };
14 }
15 
16     //var box =new Box();
17     //alert(box.constructor == Box);            //true
18     
19     //重写原型对象
20     Box.prototype={
21         age:200;            //这里不会保留之前原型的任何信息了
22                             //把原来的原型对象和构造函数对象实例之前的关系切断了。
23     }
24     
25     var box =new Box();
26     alert(box.run());            //run 已经不存在了 因为从写了原型

 

★原型对象还可以在ECMAScript内置的引用类型都可以使用这种方法

 1 //数组排序
 2 var box = [5,1,6,9,3,5,8];
 3 alert(box.sort());
 4 
 5 //查看sort是否是Array原型对象里的方法
 6 alert(Array.prototype.sort);
 7 alert(String.prototype.substring);
 8 
 9 //内置引用类型的功能的扩展
10 String.prototype.addstring =function()
11 {
12     return this+'被添加了!';
13 }
14 
15 alert('Lee'.addstring()); 

 

posted on 2015-03-04 15:55  VANQUISHER  阅读(93)  评论(0编辑  收藏  举报

导航