拿這個例子:javascript原型上的屬性與對象有什麼區別?
var personPrototype = {
firstName: '',
lastName: '',
getFullname: function() {
return this.firstName + ' : ' + this.lastName;
}
}
Person = {
};
function newPerson(firstName, lastName) {
var Person = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype = personPrototype;
return new Person(firstName, lastName);
}
var p1 = newPerson('someone', 'else');
var p2 = newPerson('john', 'doe');
console.log(p1.getFullname());
console.log(p2.getFullname());
從personPrototype移動名字和姓氏的人得到相同的結果。這是否意味着兩者之間沒有區別,還是我忽略了某些東西?
您不應該每次在'newPerson'工廠函數中重新創建'Person'構造函數。如果您想使用工廠函數,請改用[Object.create'](http://stackoverflow.com/a/39546963/1048572)。 – Bergi