深入之创建对象的多种方式以及优缺点

// 1. 工厂模式
//缺点:对象无法识别,因为原型都指向Object
function pe() {
    var o = new Object();
    o.name = name;
    o.getname = function() {
        console.log(this.name)
    }
    return o
}


// 2. 构造函数模式
// 优点:实例可以识别为一个特定的类型
// 缺点:每次创建实例每个方法都要被创建一次
function Person(name) {
    this.name = name;
    this.getName = function() {
        console.log(this.name);
    };

}
var person = new Person('zhansan');

// 2.1 构造函数模式优化
// 优点:解决了每个方法都要被重新创建的问题
// 缺点:这叫啥封装……
function Person(name) {
    this.name = name;
    this.getName = getName;

}

function getName() {
    console.log(this.name);
}
var person = new Person('zhansan');

// 3. 原型模式
// 优点:方法不会重新创建
// 缺点:1. 所有的属性和方法都共享 2. 不能初始化参数
function Person(name) {

};
Person.prototype.name = 'keivn';
Person.prototype.getName = function() {
    console.log(this.name);
};

var person1 = new Person();

// 3.1 原型模式优化
// 优点:封装性好了一点
// 缺点:重写了原型,丢失了constructor属性
function Person(name) {

};
Person.prototype = {
    name: 'kevin',
    getName: function() {
        console.log(this.name);
    }
};

var person1 = new Person();

// 3.2 原型模式优化
// 优点:实例可以通过constructor属性找到所属构造函数
// 缺点:原型模式该有的缺点还是有
function Person(name) {

}

Person.prototype = {
    constructor: Person,
    name: 'kevin',
    getName: function() {
        console.log(this.name);
    }
};

var person1 = new Person();


// 4. 组合模式
// 优点:该共享的共享,该私有的私有,使用最广泛的方式
// 缺点:有的人就是希望全部写在一起,即更好的封装性
function Person(name) {
    this.name = name;
}

Person.prototype = {
    constructor: Person,
    getName: function() {
        console.log(this.name);
    }
};

var person1 = new Person();

// 4.1 动态原型模式
// 注意:使用动态原型模式时,不能用对象字面量重写原型
function Person(name) {
    this.name = name;
    if (typeof this.getName != "function") {
        Person.prototype.getName = function() {
            console.log(this.name);
        }
    }
}

var person1 = new Person();
// 如果你就是想用字面量方式写代码,可以尝试下这种:
function Person(name) {
    this.name = name;
    if (typeof this.getName != "function") {
        Person.prototype = {
            constructor: Person,
            getName: function() {
                console.log(this.name);
            }
        }

        return new Person(name);
    }
}

var person1 = new Person('kevin');
var person2 = new Person('daisy');
原文地址:https://www.cnblogs.com/xzma/p/8543434.html