2

A lot of scripts dynamically create images, such as

            im = new Image();
            im.src = 'http://...';

I am looking for overloading of constructor for Image class with feature to add a reference of each newly created object to some array.

Let's say I have

            var dynImages = new Array;

And then I want each new dynamically created image to be in my dynImages array, so then I can anytime access src of each of image that was created by new Image() by dynImages.

Possible?

Ωmega
  • 42,614
  • 34
  • 134
  • 203

2 Answers2

3

Something like:

var dynImages = new Array;
Image = (function (org) {
    return function () {
        var result = new org;
        dynImages.push(result);
        return result;
    };
}(Image));


var tmp = new Image();
tmp.src = 'http://www.google.de/images/srpr/logo3w.png';
document.body.appendChild(tmp);​

console.log(dynImages);

​http://jsfiddle.net/EkQmL/

though I did only test this in chrome.

Yoshi
  • 54,081
  • 14
  • 89
  • 103
  • Will it work also without call of `appendChild`? Not all images have to be appended. – Ωmega Mar 12 '12 at 23:27
  • Well just try removing the line and watch the console ;) For me it still works, though Marshall has some very valid points regarding this kind of code. You'll probably have some browser testing to do. ;) – Yoshi Mar 12 '12 at 23:29
2

Image is a native. So overloading it's constructor is not a great idea. It's possible that you could add to its prototype. Or, you could make your own constructor, like this:

var dynImages = [];
var dynImg = function(path) {
    var img = new Image();
    img.src = path;
    dynImages.push(img);
    return img;
};

// now to make an image
var imageOne = dynImg('asdf.jpg');
// and another
var imageTwo = dynImg('xyz.gif');

// dynImages is now [<img src='asdf.jpg'>, <img src='xyz.gif'>]
Marshall
  • 4,716
  • 1
  • 19
  • 14
  • I was not clear enough. I meant to keep name of class Image, so `new Image()` will be used, not `new dynImage()`. I want to store URLs (src) of all images to my array. – Ωmega Mar 12 '12 at 23:10
  • Right, but as I mentioned Image is a native object, containing some qualities specific to itself. Some browsers won't even let you overload. Others, like Chrome, will let you (by doing something like `Image = function() { ... }` but you may lose those special `Image` qualities. It's bad practice to overload natives, and is simply dangerous. – Marshall Mar 12 '12 at 23:18
  • For overloading the constructor, you should check http://stackoverflow.com/questions/8717226/override-image-constructor-in-js - if you really want to. Overloading natives is just bad practice. Try extending the object like it's shown above. It is not only safer, it also provides reusability. – arvidkahl Mar 12 '12 at 23:19