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

相關文章
相關標籤/搜索