我想创建这个类的几个实例
var fruit = {
texture: new Image(),
speed: 5,
x: 0,
y: 0,
};
function fruits(speed, x, y)
{
fruit.speed = speed;
fruit.x = x;
fruit.y = y;
return fruit;
};
但是当我创建新对象时,所有值都被最后创建的对象覆盖了。我该如何修复? 我的循环:
var apples = [];
for(var i = 0; i < 10; i++)
{
apples[i] = new fruits(5, Math.floor((Math.random()*775)+1), 0);
apples[i].texture.src = "_img/apple.png";
}
最佳答案
这里出现的其他答案很奇怪。这是解决方案:
function fruits(speed, x, y)
{
this.texture = new Image( );
this.speed = speed;
this.x = x;
this.y = y;
};
请注意关键字this
用于设置属性。这意味着当你调用
var apple = new fruits( blah blah );
然后 apple
将被设置为一个新对象,该对象具有 texture
、speed
、x
和 y
属性。不需要引用一些全局对象来存储这些;它们存储在新创建的对象本身中。
另外我会重命名它;惯例是对对象使用单数名称和首字母大写,因此 Fruit
会更有意义(允许 new Fruit(...)
)
关于javascript - 对象 Javascript 的几个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20313266/