zoukankan      html  css  js  c++  java
  • 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)

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

  • 相关阅读:
    OpenSSL 安装 (Linux系统)
    JVM 指令集
    Github清除历史提交,保留最新提交
    php7+apache2.4 安装(window)
    mysql 函数模拟序列
    SpringBoot配置成Liunx服务
    Liunx下NFS服务器的搭建与配置
    Laravel 出现"RuntimeException inEncrypter.php line 43: The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths."问题的解决办法
    win7安装laravel
    win7安装composer
  • 原文地址:https://www.cnblogs.com/tkj-ci/p/4311180.html
Copyright © 2011-2022 走看看