javascript prototype 初步理解

 

阅读 “華安” 写的 JavaScript中对象的prototype属性 的个人理解

此段代码仅仅是为了理解prototype而写的, 还有许多需要修改的地方,若想了解更多,还是建议阅读 華安 本人写的 js实现继承等多篇文章

       function point(x,y){
                if(x) this.x = x;    
                if(y) this.y = y;
            }
            point.prototype.x=0;
            point.prototype.y=0;
            
            /**
            将一个对象设置为一个类型的原型,相当于通过实例化这个类型,为对象建立只读副本,
            在任何时候对副本进行改变,都不会影响到原始对象,
            而对原始对象进行改变,则会影响到副本,
            除非被改变的属性已经被副本自己的同名属性覆盖。用delete操作将对象自己的同名属性删除,则可以恢复原型属性的可见性。    
            以上一段话分为四个方面理解
            1、 将 m_firstPoint 设置为 GETTER的原型,相当于实例化 GETTER这个类型, 返回新的 GETTER对象
            2、 对GETTER 的修改不会影响到 m_firstPoint 即 原始对象
            3、 如果修改了 m_firstPoint 属性的原始值, 则会影响到副本 GETTER 的属性值
            4、 如果m_firstPoint 的 属性x 被 副本 GETTER的同名属性覆盖(即 GETTER.prototype.x = 200)了,
                则,原始类型的值也就改变,除非通过 delete GETTER.x, 才可以回复原型属性的值
            
            **/
            function LineSegment(p1,p2){
                var m_firstPoint = p1;    //p1 对象
                var m_lastPoint = p2;    //p2 对象
                this.getFirstPoint = function(){
                    function GETTER(){};
                    //GETTER.prototype 是 m_firstPoint 的副本 (将一个对象设置为一个类型的原型,相当于通过实例化这个类型)
                    GETTER.prototype = m_firstPoint; 
                    //GETTER.prototype.x = 200;
                    return new GETTER();            //返回副本对象
                }
                this.getLastPoint = function(){
                    function GETTER(){};
                    GETTER.prototype = m_lastPoint;
                    return new GETTER();
                }
            }
            var p1 = new point();
            var p2 = new point(2,3);
            var line1 = new LineSegment(p1,p2);
            var p = line1.getFirstPoint();
            p.x=100;
            console.log(p1.x);
            console.log(p.x)

若有不妥之处,还望指出,共同进步!

posted @ 2015-03-03 15:59  刺_马克变色杯  阅读(138)  评论(0编辑  收藏  举报