• Javascript 创建对象


    一、工厂模式

    function createPerson(name,age,job){
                var o=new Object();
                    o.name=name;
                    o.age=age;
                    o.job=job;
                    o.sayHi=function(){
                        alert(this.name);
                    };
                return o;
            }
            var person1=createPerson("xiaoming",29,"student");

    二、构造函数模式

    function Person(name,age,job){
            this.name=name;
            this.age=age;
            this.job=job;
            this.sayHi=function(){
                alert(this.name);
            };
        };
        var person2=new Person("xiaohong",29,"doctor");

    三、原型模式

    function Person2(){};
        Person2.prototype.name="xiaoming";
        Person2.prototype.age=20;
        Person2.prototype.job="Doctor";
        Person2.prototype.sayHi=function(){
            alert("Hi!");
        };
        person4=new Person2();
        person4.name="newPerson";

    四、构造函数和原型的混血

    function Person(name,age,job){
            this.name=name;
            this.age=age;
            this.job=job;
            this.friends=["hebe","ella"];
        };
        Person.protoptype={
            constructor:Person,
            sayName:function(){
                alert(this.name);
            }
        }
    var person=new Person("xiaoming",20,"Doctor");

    五、动态原型模式

        function Person(name,age,job){
            this.name=name;
            this.age=age;
            this.job=job;
            if(typeof this.sayName!="function"){
                Person.prototype.sayName=function(){
                    alert(this.name);
                }
            };
        };
        var friend=new Person("xiaoming",20,"Doctor");

    六、寄生构造函数——构造函数和工厂模式的混血

    function Person(name,age,job){
            var o=new Object();
            o.name=name;
            o.age=age;
            o.job=job;
            o.sayName=function(){
                alert(this.name);
            };
            return o;
        }
        var friend=new Person("hi",29,"Doctor");

    七、稳妥构造函数

    function Person(name,age,job){
            var o=new Object();
                o.sayName=function(){
                    alert(name);
                };
            return o;
        }
    var person=Person("xiaoming",20,"Doctor");
    放下过去,才能迎接未来! 未来的每一天我都要过的精彩!
  • 相关阅读:
    畅通project续
    mysql两列合成一列
    stl 之set图解
    Random Forest 与 GBDT 的异同
    手机游戏加密那点事儿_前言_0
    onfocus事件,onblur事件;Focus()方法,Blur()方法
    Oracle数据库导出导入
    数据文件限制大小
    oracle级联操作
    Material UI:很强大的CSS框架
  • 原文地址:https://www.cnblogs.com/lilylearning1992/p/4757697.html
Copyright © 2020-2023  润新知