• JS面向对象——动态原型模型、寄生构造模型


    动态原型模型

    组合使用构造函数模型和原型模型,使得OO语言程序员在看到独立的构造函数和原型时很困惑。动态原型模型致力于解决该问题,它把所有的信息封装在构造函数中,通过在构造函数中初始化原型(仅在必要情况下),同时又使用构造函数和原型的优点。

    实例代码如下:

    <!DOCTYPE html>
    <html>
    <head>
        <title>动态原型模型</title>
        <script type="text/javascript">
            //动态原型模型:把所有的信息封装在构造函数中。通过在构造函数中初始化原型(仅在必要情况),又保持了同时使用构造函数和原型模型的优点。    
            function Student(name,age,sex){            
                this.name=name;
                this.age=age;
                this.sex=sex;
                this.friends=["Kitty","Court"];    
                if(typeof this.sayName!="function"){
                    //不能使用对象字面量重写原型
                    Student.prototype.sayName=function(){
                    alert(this.name);
                    };
                }
            }
    
            var stu1=new Student("Lucy",10,"girl");
            stu1.sayName();
            var stu2=new Student("Bob",9,"boy");
            stu2.sayName();        
            stu1.friends.push("Van");
            alert(stu1.friends);//"Kitty,Court,Van"
            alert(stu2.friends);//"Kitty,Court"
            alert(stu1.friends===stu2.friends);//false
            alert(stu1.sayName===stu2.sayName);//true
        </script>
    </head>
    <body>
    </body>
    </html>

    寄生构造函数模型

    基本思想:创建一个函数,该函数作用仅仅是封装创建对象的代码,然后返回新创建的对象。

    以下代码说明该模型基本思想:

    <!DOCTYPE html>
    <html>
    <head>
        <title>寄生构造函数模型</title>
        <script type="text/javascript">            
            function Student(name,age,sex){    
                var  o=new Object();    
                o.name=name;
                o.age=age;
                o.sex=sex;
                o.friends=["Kitty","Court"];    
                o.sayName=function(){
                    alert(this.name);
                    };
                return o;
            }
    
            var stu1=new Student("Lucy",10,"girl");
            stu1.sayName();
            alert(stu1 instanceof Student);    //false
            alert(stu1 instanceof Object);//true
        </script>
    </head>
    <body>
    </body>
    </html>

    注:返回的对象与构造函数或者与构造函数的原型属性之间没有任何关系;即:构造函数返回的对象与在构造函数外部创建的对象没什么不同。不能依赖instanceof操作符来确定对象类型。

    这种模式常用在特殊情况下为对象创建构造函数。

  • 相关阅读:
    nginx常用配置
    docker 启动常用容器命令
    win10 安装 docker
    Selenium IDE for Google Chrome
    Python use goto statement
    TCP:一个悲伤的故事
    gtx770测评
    三十而立——年终总结
    bilibili自定义调整视频播放速度
    linux-安装docker
  • 原文地址:https://www.cnblogs.com/planetwithpig/p/11531122.html
Copyright © 2020-2023  润新知