简体   繁体   中英

javascript prototype inheritance override property

I have created collection base class/object to do the repeated task. I have CollectionBase, and I have Persons class that inherit to CollectionBase. but my problem is when i create 2 persons collection like persons1 = new Persons() and persons2 = new Persons() it seems that they have same reference object. Any suggestion on how i can make everytime i will create a new Persons it will create new instance.

Please refer to this on plnkr; http://plnkr.co/edit/8GPkWO4nKRiskxoRWrkg?p=info

(function(){

    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();

})();

Any properties assigned to the prototype are shared among all objects that use that prototype (since the prototype object itself is shared among all instances). This is great for functions on the prototype (eg methods), but it is usually bad for data properties because (as you have found), all instances share the same data properties which is not what you usually want.

The usual way to handle this is to assign data properties in your constructor, NOT in the prototype. This creates a new data variable for each new instance of the object.

function CollectionBase(){
   // create new value property for each instance
   this.value = [];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM