1

工厂模式(不推荐)

var sayName = function(){
    return this.name;
};

function createPerson(name,age){
    var obj = {};
    obj.name = name;
    obj.age = age;
    obj.sayName = sayName;
    return obj;
}

var newPerson = createPerson("Oliver",18);
console.log(newPerson.sayName());
  1. 应该把方法放在函数的外面,避免重复创建该方法;

  2. 定义的不是构建函数,因该使用var 方法创建实例,而不是new 方法;

  3. 不要忘记在函数的最后return obj;

构造函数模式(不推荐)

var sayName = function(){
    return this.name;
};

function Person(name,age){
    this.name = name;
    this.age = age;
    this.sayName = sayName;
}

var newPerson = new Person("Oliver",18);
console.log(newPerson.sayName());
  1. 使用this指代,函数无需明确return;

  2. 应该把方法放在函数的外面,避免重复创建该方法;

原型模式(不推荐)

var sayName = function(){
    return this.name;
};

function Person(){};
Person.prototype.name = "Oliver";
Person.prototype.age = 18;
Person.prototype.sayName = sayName;

var newPerson = new Person("Oliver",18);
console.log(newPerson.sayName());
  1. 函数中不对属性进行定义而是用prototype;

组合使用构造函数模式和原型模式(推荐)

function Person(name,age){
    this.name = name;
    this.age = age;
};

Person.prototype.sayName = function(){
    return this.name;
};

var newPerson = new Person("Oliver",18);
console.log(newPerson.sayName());
  1. 将所有属性定义在函数中(构造函数方式);将所有方法定义在prototype中(原型方式);

动态原型模式(推荐)

function Person(name,age){
    this.name = name;
    this.age = age;
    if (typeof Person.sayName != "function"){
        Person.prototype.sayName = function(){
            return this.name;
        };
    }
};
var newPerson = new Person("Oliver",18);
console.log(newPerson.sayName());
  1. 这里判断属性是否为function 以避免重复创建;


JS菌
6.4k 声望2k 粉丝