JavaScript Image constructor overload?

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?

Answers:

Answer

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.

Answer

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'>]

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.