javascript prototype inheritance override property -
javascript prototype inheritance override property -
i have created collection base of operations class/object repeated task. have collectionbase, , have persons class inherit collectionbase. problem when create 2 persons collection persons1 = new persons() , persons2 = new persons() seems have same reference object. suggestion on how can create everytime create new persons create new instance.
please refer on plnkr; http://plnkr.co/edit/8gpkwo4nkriskxorwrkg?p=info
(function(){
function collectionbase(){ this.collection = []; } object.defineproperties(collectionbase.prototype, { count: { get: function(){ homecoming this.collection.length; }, enumerable: true } }); collectionbase.prototype.init = function(){ }; collectionbase.prototype.get = function(index){ if (index === undefined){ homecoming this.collection; } homecoming this.collection[index]; }; collectionbase.prototype.remove = function(index){ try{ if (index === undefined) throw new error('index 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();
})();
any properties assigned prototype shared among objects utilize prototype (since prototype object shared among instances). great functions on prototype (e.g. methods), bad info properties because (as have found), instances share same info properties not want.
the usual way handle assign info properties in constructor, not in prototype. creates new info variable each new instance of object.
function collectionbase(){ // create new value property each instance this.value = []; }
javascript inheritance prototype
Comments
Post a Comment