Is it possible to associate an image as an attribute with an Object in Javascript like this? 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?
There was also a syntax error (well, actually two):
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
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";
you will get an error
"Uncaught ReferenceError: icon is not defined"
as the icon is not declared or refered anywhere in the code. icon
is a property of the spy
object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.