[英]javascript prototype inheritance override property
我已经创建了集合基类/对象来执行重复的任务。 我有CollectionBase,并且有继承到CollectionBase的Persons类。 但是我的问题是,当我创建2个人集合(例如person1 = new Persons()和person2 = new Persons())时,它们似乎具有相同的引用对象。 关于每次如何创建新建议的任何建议都会创建新实例。
请在plnkr上参考此内容; http://plnkr.co/edit/8GPkWO4nKRiskxoRWrkg?p=info
(功能(){
function CollectionBase(){
this.collection = [];
}
Object.defineProperties(CollectionBase.prototype, {
count: {
get: function(){
return this.collection.length;
},
enumerable: true
}
});
CollectionBase.prototype.init = function(){
};
CollectionBase.prototype.get = function(index){
if (index === undefined){
return this.collection;
}
return this.collection[index];
};
CollectionBase.prototype.remove = function(index){
try{
if (index === undefined) throw new Error('index is undefined');
this.collection.splice(index, 1);
}
catch(err){
console.log(err);
}
};
CollectionBase.prototype.update =function(item){
};
CollectionBase.prototype.add = function(item){
this.collection.push(item);
};
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
function Persons(){
CollectionBase.call(this);
}
Persons.prototype = Object.create(CollectionBase.prototype);
var persons1 = new Persons();
var persons2 = new Persons();
})();
分配给原型的任何属性都在使用该原型的所有对象之间共享(因为原型对象本身在所有实例之间都是共享的)。 这对原型上的函数(例如方法)很有用,但对数据属性通常不利,因为(如您所发现的)所有实例共享相同的数据属性,这通常不是您想要的。
解决此问题的通常方法是在构造函数中分配数据属性,而不是在原型中分配数据属性。 这将为对象的每个新实例创建一个新的数据变量。
function CollectionBase(){
// create new value property for each instance
this.value = [];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.