原型中定义的数组跨实例共享

时间:2018-02-10 05:22:16

标签: javascript

我不确定为什么js在两个实例之间共享数组而不是其他属性。有人愿意帮忙解决这个问题吗?我也没试过原型就试过了。我得到同样的东西

function ItemScroller() {};

ItemScroller.prototype = {

// var ItemScroller = {

    items: [],
    itemCount: 0,
    position: 0,

    InsertItem: function( item ) {

        this.items.push( item );
        this.itemCount++;
    },

    DisplayPosition: function() {

        this.items[this.position].style.display = "block";
    },

    NextItem: function() {

        if ( this.position < this.itemCount - 1 ) {
            this.items[this.position].style.display = "none";
            this.position++;
            this.items[this.position].style.display = "block";
        }
    },

    PreviousItem: function() {

        if ( this.position != 0 ) {
            this.items[this.position].style.display = "none";
            this.position--;
            this.items[this.position].style.display = "block";
        }
    },

};

使用上述定义,

var one = new ItemScroller();
//var one = Object.create(ItemScroller);
var two = new ItemScroller();
//var two = Object.create(ItemScroller);

for ( var i = 0; i < 4; i++) {
    one.InsertItem("sick");
}

for ( var i = 0; i < 2; i++) {
    two.InsertItem("ok");
}

然后显示每个内容 -

console.log(one.itemCount); //output: 4
console.log(one.items); //output: [sick, sick, sick, sick, ok, ok]

上面打印4和一个数组中的所有六个项目

console.log(two.itemCount); //output: 2
console.log(two.items); //output: [sick, sick, sick, sick, ok, ok]

上面打印2和两个数组中的所有六个项目

我期待以下情况 -

console.log(one.itemCount); //output: 4
console.log(one.items); //[sick, sick, sick, sick]

console.log(two.itemCount); //output: 2
console.log(two.items); //output: [ok, ok]

2 个答案:

答案 0 :(得分:0)

你的实施还不正确。因为您将itemsitemCountposition放在prototype中。 Prototypeinstances Class的共享内存。

one instanceof ItemController // true
two instanceof ItemController // true
one._proto__ // prototype object of class, included items.
two._proto__ // prototype object of class, included items.
one.items === two.items === ItemController.prototype.items // true, because two of this are pointed to the same reference. It's ItemController.prototype.items

解决问题:在构造函数中将每个瞬间不想共享的属性放入。代码应该是这样的:

function ItemScroller() {
   this.items = [];
   this.itemCount = 0;
   this.position = 0;
};

ItemScroller.prototype = {
    InsertItem: function( item ) {
    },

    DisplayPosition: function() {

    },

    NextItem: function() {

    },

    PreviousItem: function() {

    },

};

因此,将为每个实例创建上述属性。

one instanceof ItemController // true
two instanceof ItemController // true
one.items === two.items // false
one.__proto__ // prototype of class, now not included item, itemCount, position...

答案 1 :(得分:0)

这将起作用:

function ItemScroller(items=[]) {
        this.items=items;
};