首页 > Web开发 > 详细

js中对prototype对象继承的理解和实例

时间:2015-12-04 20:24:37      阅读:272      评论:0      收藏:0      [点我收藏+]

关于js中prototype的理解:

 1 ///Javascript继承机制的设计思想引用http://www.ruanyifeng.com/blog/2011/06/designing_ideas_of_inheritance_mechanism_in_javascript.html
 2 //一个对象都是一个构造函数的实例化  所有的需要共享的方法和属性都放在了prototype中,成为prototype的属性或者方法
 3 //而私有的方法和属性则放在构造函数中
 4 
 5 //关于prototype的测试实验
 6 function Animail(name){
 7     this.name = name ;
 8 }
 9 Animail.prototype.spcize = "1"; //spcize 需要共享的属性或者方法
10 
11 
12 
13 
14 var a1 = new Animail("apple");
15 var a2 = new Animail("banana");
16 
17 //这边是用的prototype的属性的引用
18 console.log(a1.spcize);
19 console.log(a2.spcize);
20 
21 //应该是重新创建了spcize对象,覆盖原来的引用,然后进行赋值(猜测)
22  a1.spcize = "2";
23  a2.spcize = "3";
24  
25  console.log(a1.spcize);
26  console.log(a2.spcize);
27  
28  delete a1.spcize;//删除对象specize之后,a1.specize编程Animail。prototype。specize的引用
29  //delete a2.spcize;
30  
31  Animail.prototype.spcize = "5"; 
32  
33  console.log(a1.spcize);
34  console.log(a2.spcize);

 

js中对prototype对象继承的一个实例:

 1 //只得考虑的原型链的一段代码
 2 //实例化triangle,去调用Triangle的构造函数,注意此时prototype是为空的,所以此时的实例化对象triangle中的prototype为空,所以之后去调用getAre报错
 3 //紧接着会去调用Ploygon构造函数,并且对Polygon的prototype进行初始化
 4 //然后对Triangle的prototype进行初始化,所以之后第二个实例化的对象就有getAre方法了。
 5 
 6 
 7 //如何更改在所有triangle对象实例化之前,先将Triangle方法的prototype与Polygon的实例化对象绑定,这是实例化triangle对象会有一个getAre的引用(链接),然后在其调用
 8 //调用实例化构造函数的时候会去重载prototype的getAre方法,因为是引用所以triangle对象的方法也被改变了。
 9 function Polygon(iSide){
10     console.log("Polygon constructor");
11     this.side = iSide;    
12     if(typeof Polygon._init == "undefined"){
13         console.log("Polygon protype");
14         Polygon.prototype.getArea = function(){
15             return 0;
16         };
17     };
18     Polygon._init = true;
19 };
20 
21 function Triangle(iBase,iHeight){
22     console.log("Triangle consturctor");
23     Polygon.call(this,3);
24     this.base = iBase ;
25     this.height = iHeight;
26     
27     if(typeof Triangle._init == "undefined"){
28         Triangle.prototype = new Polygon();  //将这句话注释掉
29         //console.log(Triangle.prototype.getArea());
30         console.log("triangle prototype");
31         
32         Triangle.prototype.getArea = function(){
33             return 0.5 * this.height * this.base;
34         };
35     };
36     Triangle._init = true;
37 };
38 //Triangle.prototype = new Polygon(); //在这添加原型与实例化对象的绑定。
39 var triangle = new Triangle(3,4);
40 
41 var triangle2 = new Triangle(3,4);
42 //console.log(triangle2.base);
43 //console.log(triangle2.height);
44 //console.log(triangle2.side);
45 console.log(triangle2.getArea());
46 console.log(triangle.getArea());

本人链接至:

http://blog.csdn.net/w329636271/article/details/21224403

http://blog.csdn.net/w329636271/article/details/21171857

如有侵权请告知,本人立即删

js中对prototype对象继承的理解和实例

原文:http://www.cnblogs.com/pm-dongjian/p/5020030.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!