javascript prototype 初步理解

 

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

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

       function point(x,y){
                if(x) this.x = x;    
                if(y) this.y = y;
            }
            point.prototype.x=0;
            point.prototype.y=0;
            
            /**
            将一个对象设置为一个类型的原型,至关于经过实例化这个类型,为对象创建只读副本,
            在任什么时候候对副本进行改变,都不会影响到原始对象,
            而对原始对象进行改变,则会影响到副本,
            除非被改变的属性已经被副本本身的同名属性覆盖。用delete操做将对象本身的同名属性删除,则能够恢复原型属性的可见性。    
            以上一段话分为四个方面理解
            一、 将 m_firstPoint 设置为 GETTER的原型,至关于实例化 GETTER这个类型, 返回新的 GETTER对象
            二、 对GETTER 的修改不会影响到 m_firstPoint 即 原始对象
            三、 若是修改了 m_firstPoint 属性的原始值, 则会影响到副本 GETTER 的属性值
            四、 若是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)

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

相关文章
相关标签/搜索