I’m programming in JavaScript and I would like to know if there is a ‘best’ method of creating multiple image objects. Take the code below as an example.
var a = new Image();
var b = new Image();
var c = new Image();
Is this the only way to do it, or should I do something like…
var a = new Image(), b = a, c = a;
I’m just wondering if there is a different way of doing the first method. I find my program contains a lot more ‘new Image()‘ variables, and I thought being repetitive was bad for the code.
I would probably build them as an array, rather than pollute your namespace with a pile of separate variables pointing to different
Imageobjects.This isn’t going to be much more or less efficient than creating multiple variables, but it is certainly easier to keep them organized. You will save a few lines of code in initializing them, but in the long run, that amounts to a micro-optimization which will have only negligible effect.
Note that if you really want a text descriptor for each
Image, you could opt to use an object{}instead of an Array[]and set its properties to small descriptive strings. You could even initialize it via an array:This borders a little on misuse of the object to behave like a PHP or Perl associative array, but will provide easy access to the images if you need them by name rather than a numeric key as in the array method above.