為了創(chuàng)建一系列相似的對象
//缺點: 每創(chuàng)建一個對象都會產(chǎn)生一個getName()副本, 并且無法確定對象類型
//優(yōu)點: 使用方便
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');
//優(yōu)點:可以繼承
//缺點 : 沒有第一種方式簡單
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);
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者