簡體   English   中英

javascript原型繼承重寫屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM