为了创建一系列相似的对象
//缺点: 每创建一个对象都会产生一个getName()副本, 并且无法确定对象类型
//优点: 使用方便
function createPerson(name) {
var person = {
getName: function() {
return name;
},
setName: function(name) {
this.name = name;
}
};
return person;
}
var p1 = createPerson('erichow');
var p2 = createPerson('lufei');
//优点:可以继承
//缺点 : 没有第一种方式简单
function inherit(Klass, Base) {
Klass.prototype = Object.create(Base.prototype);
Klass.prototype.constructor = Klass;
Klass.prototype.super = function() {
Base.apply(this, arguments);
}
}
function Person(name) {
this.name = name;
}
Person.prototype.setName = function(name) {
this.name = name;
}
function Student(name, age) {
this.super(name);
this.age = age;
}
inherit(Student, Person);
var p1 = new Person('erichow');
var s1 = new Student('lufei', 34);