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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Will it work also without call of appendChild? Not all images have to be appended.
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. ;)
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'>]

3 Comments

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.
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.
For overloading the constructor, you should check stackoverflow.com/questions/8717226/… - 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.