[英]Associating an icon with an object
Is it possible to associate an image as an attribute with an Object in Javascript like this? 是否可以像这样将图像作为属性与Java中的对象相关联? So far I have not been able to get it to work.
到目前为止,我还无法使其正常工作。
var spy={
name: "Spy",
life: true,
voting: true,
icon: new Image();
}
icon.src = "Images/testImage";
When you want to access or modify an object's property, you can't just access the property name directly. 当您要访问或修改对象的属性时,不能仅直接访问属性名称。 You'll have to access an object property like this:
您必须像这样访问对象属性:
var spy={
name: "Spy",
life: true,
voting: true,
icon: new Image()
};
spy.icon.src = "Images/testImage";
Otherwise, if you had several "spy" objects, how were the JavaScript compiler to know which one's property you want to change? 否则,如果您有多个“间谍”对象,那么JavaScript编译器如何知道要更改的属性?
There was also a syntax error (well, actually two): 还有一个语法错误(实际上是两个):
new Image()
. new Image()
后面的分号。 You do not need and simply cannot put a semicolon in an object declaration that way. You need to access the src
property by spy.icon.src
您需要通过
spy.icon.src
访问src
属性
var spy={
name: "Spy",
life: true,
voting: true,
icon: new Image()
};
spy.icon.src = "Images/testImage";
If you try to access the src
property like icon.src = "Images/testImage";
如果您尝试访问
src
属性,例如icon.src = "Images/testImage";
you will get an error 你会得到一个错误
"Uncaught ReferenceError: icon is not defined"
“未捕获的ReferenceError:图标未定义”
as the icon is not declared or refered anywhere in the code. 因为图标未在代码中的任何地方声明或引用。
icon
is a property of the spy
object. icon
是spy
对象的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.