简体   繁体   English

javascript原型继承重写属性

[英]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. 我有CollectionBase,并且有继承到CollectionBase的Persons类。 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. 但是我的问题是,当我创建2个人集合(例如person1 = new Persons()和person2 = new Persons())时,它们似乎具有相同的引用对象。 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; 请在plnkr上参考此内容; http://plnkr.co/edit/8GPkWO4nKRiskxoRWrkg?p=info 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); 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 = [];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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