Sven Knockaert Sven Knockaert - 6 months ago 12
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
img.src
. Do I have to set the src afterwards or is there a workaround?

Answer

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 = "http://i.stack.imgur.com/KUvWS.jpg";
    return img;
  })()
};

console.log("img src: %o", obj.img.src);
<!-- console visualization; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>