js 创建对象

1.工厂模式

        function createPerson(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 person1 = createPerson("Nicholas", 29, "Software Engineer");
        var person2 = createPerson("Greg", 62, "Doctor");

2.构造函数模式

        function Person(name, age, job) {
            this.name = name;
            this.age = age;
            this.job = job;
            this.sayName = function () {
                alert(this.name);
            };
        }
        var person1 = new Person("Nicholas", 29, "Software Engineer");
        var person2 = new Person("Greg", 62, "Doctor");
        //与工厂模式的不同点
        //1.没有显示创造对象
        //2.直接将属性和方法赋值给this
        //3.没有return语句
        //4.使用new创造对象

        //使用方式
        //1.当做构造函数使用
        var person = new Person("Nicholas", 29, "Software");
        person.sayName();//Nicholas

        //2.作为普通函数调用
        Person("Yellow", 27, "Doctor");
        window.sayName();//Doctor

        //3. 在另一个对象的作用域中调用
        var o = new Object();
        Person.call(o, "King", 25, "Nurse");
        o.sayName();//King
        
        //缺点:每个方法都要在每个实例上重新创建一遍

3.原型模式

        function Person() {
        }
        Person.prototype.name = "Yellowshorts";
        Person.prototype.age = 29;
        Person.prototype.job = "Software";
        Person.prototype.sayName = function () {
            alert(this.name);
        }
        var person1 = new Person();
        person1.sayName();//Yellowshorts

        var person2 = new Person();
        person2.sayName();//Yellowshorts

        alert(person1.sayName == person2.sayName);//true

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。