###一、工厂模式function createPerson(name, age, job) { var o = new Object(); o.name = name; o.age
###一、工厂模式
function createPerson(name, age, job) { var o = new Object(); o.name = name; o.age = age; o.job = job; o.getName = function () { return this.name; } return o;//使用return返回生成的对象实例}var person = createPerson('Jack', 19, 'SoftWare Engineer');
缺点:无法识别对象类型,因为创建对象都是使用Object的原生构造函数来完成的;每个对象都有自己的getName 函数,不能共享同一个函数。###二、构造函数方式
function Person(name,age,job){ this.name = name; this.age = age; this.job = job; this.getName = function () { return this.name; }}var person1 = new Person('Jack', 19, 'SoftWare Engineer');var person2 = new Person('Liye', 23, 'Mechanical Engineer');
缺点:构造函数会重复生成函数,不能共享同一个函数。###三、原型方式
function Person(){}Person.prototype.name = 'Jack';//使用原型来添加属性Person.prototype.age = 29;Person.prototype.getName = function(){ return this.name;}
缺点:构造函数没有参数,不能通过构造函数初始化属性值;属性是对象时被多个实例共享容易产生问题。###四、组合构造函数及原型模式
function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.lessons = ['Math', 'Physics'];}Person.prototype.getName=function(){ return this.name;}
优点:所有非函数属性都在构造函数创建可以用构造函数赋予属性默认值,所有实例共享一个方法,没有浪费内存,没有副作用【推荐】。###五、动态原型方法
function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.lessons = ['Math', 'Physics']; if(typeof Person._initialized=="undefined") { Person.prototype.getName=function() { return this.name; } Person._initialized=true; }}
优点:拥有方法四的优点同时更像其他语言中类的定义了。【推荐】
最终结论:推荐使用组合构造函数及原型模式和动态原型方法(jQuery类型的封装就是使用组合模式)。