IVYGOU / JavaScript

Learning Notes for JavaScript
0 stars 0 forks source link

构造函数模式与工厂模式的区别? #10

Open IVYGOU opened 8 years ago

IVYGOU commented 8 years ago

工厂模式可创建多个相似对象,但没有解决对象识别问题(即怎样知道一个对象的类型)?

IVYGOU commented 8 years ago

工厂模式

以函数封装以特定接口创建对象的细节。

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", 27, "Doctor");

可创建多个相似对象,但没有解决对象识别问题(即怎样知道一个对象的类型)

构造函数模式

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", 27, "Doctor");

工厂模式建立的对象只是object的实例,构造模式建立的对象既是object的实例,又是Person的实例,可以用于继承等。(所有对象都是object的实例)