使用数组从对象内加载图像

时间:2015-06-19 03:41:16

标签: javascript javascript-objects

我有一个我创建的课程,名为Sprite:

var Sprite = function Sprite()
{
that = this;
that.xPos = 0;
that.yPos = 0;
…
that.image = null;

this.render =function()
{
…
}
this.setImage(filename)
{
  that.image = new Image();
  that.image.src = filename;
}

}

然后我创建了一个对象数组:

var names=[
{filename:"a1.png"},
{filename:"a2.png"},
{filename:"a3.png"},
{filename:"a4.png"}
];

var objs = [];
for(var l=0;l<names.length;l++)
{
  objs.push({});
  objs[l] = new Sprite();
  …
  setImage(names[l]);

}

我的数组中的每个对象都指向同一个图像(使用相同的图像文件。)

有谁能告诉我这里我做错了什么?

我有更好的方法吗?

感谢。

1 个答案:

答案 0 :(得分:1)

你的setImage(names [l]);在循环中似乎是覆盖因此你得到相同的图像,尝试做类似的事情:

var Sprite = function Sprite() {
    that = this;
    that.xPos = 0;
    that.yPos = 0;
    that.image = null;

    this.setImage = function(filename) {
      that.image = new Image();
      that.image.src = filename;
    };
}

var names=[
    {'filename':"a1.png"},
    {'filename':"a2.png"},
    {'filename':"a3.png"},
    {'filename':"a4.png"}
];

var objs = [];
for(var l=0;l<names.length;l++) {
  var sp = new Sprite();
  //set image for the new sprite object
  sp.setImage(names[l].filename); 
  objs.push(sp);  //push sp object to objs array
}
console.log( objs );