JavaScript Overloading the JavaScript constructor?

Many scripts dynamically create images, such as

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

I am looking for constructor overloading for the Image class with the function of adding a reference to each newly created object in some array.

Say I have

            var dynImages = new Array;

And then I want every new dynamically created image to be in my array dynImages, so I can access srcevery image that was created new Image()on at any time dynImages.

Possible?

+1
source share
2 answers

Sort of:

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/

although I checked it only in chrome.

+3
source

Image . - . , prototype. , :

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

All Articles