Sven Knockaert Sven Knockaert - 1 year ago 67
Javascript Question

Is it possible to set an image source on a javascript object property?

Take this piece of code into consideration:

var obj = {
width : 10,
height : 10,
img : new Image(),
img.src : "assets/img.png" // this is where I get an error

I get an error on
. Do I have to set the src afterwards or is there a workaround?

Answer Source

Yes, you have to set it aftwards unless you want to wrap your img initialization in an IIFE:

var obj = {
  width: 10,
  height: 10,
  img: (function() {
    var img = new Image();
    img.src = "";
    return img;

console.log("img src: %o", obj.img.src);
<!-- console visualization; see -->
<script src=""></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download