-1

我想将精灵的位置封装在另一个对象中。这样我就可以通过and访问而不是使用tile.xand 。tile.ytile.position.xtile.position.y

然而,一旦我tile.position在 init-method中设置了 tile-object 的所有实例的值,所有实例都会更改为相同的值。这是为什么?

当我设置tile.x一切按预期工作时,这意味着每个对象都获得了正确的值。

这就是我创建多个实例的方式:

在 for 循环中,我正在创建所述对象的多个实例:

for (var y = 0; y < 10; ++y) {
  for (var x = 0; x < 10; ++x) {
    var tile = Object.create(tileProperty);
    tile.init(x, y);
    ...
  }
}

这是克隆的对象:

var tileProperty = {
    // this works
    x: null, 
    y: null,
    // this will get changed for ALL instances
    position: { 
        x: null,
        y: null
    },
    init: function(x, y) {
        this.name = x.toString() + y.toString();
        this.x = x;
        this.y = y;
        this.position.x = x;
        this.position.y = y;
        this.canvas = document.createElement('canvas');
        var that = this;
        $(this.canvas).bind('click', function() {
            console.log(that.position, that.x, that.y);
        });

        document.body.appendChild(this.canvas);
    }
}
4

2 回答 2

1

position在所有对象中都引用了同一个对象。

您应该做的是使用标准原型解决方案

function tileProperty() {
    this.position = { 
        x: null,
        y: null
    };
}
tileProperty.prototype.init = function(x, y) {
    this.name = x.toString() + y.toString();
    this.x = x;
    this.y = y;
    this.position.x = x;
    this.position.y = y;
    this.canvas = document.createElement('canvas');
    var that = this;
    $(this.canvas).bind('click', function() {
        console.log(that.position, that.x, that.y);
    });

    document.body.appendChild(this.canvas);
}

然后使用构建您的实例

var tp = new tileProperty();
于 2012-12-11T14:00:27.400 回答
1

用这个:

var tileProperty = {
    position: { // we will inherit from this
        x: null,
        y: null,
        init: function(x, y) {
            this.x = x;
            this.y = y;
        }
    },
    init: function(x, y) {
        this.name = x.toString() + y.toString();
        // create an own Position object for each instance
        this.position = Object.create(this.position);
        // and initialize it
        this.position.init(x, y); // you might inline this invocation of course
        …
    },
    …
}
于 2012-12-11T14:59:16.413 回答