4

Is it possible to override the Image constructor in JS? So that, for example, every time a new Image() is created, a message is written to the console?

Fluffy
  • 27,504
  • 41
  • 151
  • 234

2 Answers2

7

Try this:

(function () {
    var OriginalImage = window.Image;
    window.Image = function (width, height) {
        console.log('New image');
        return new OriginalImage(width, height);   
    }
}());

Not sure if it will work in all browsers.

Anyway it is not best idea to override built in types (unless you want to use it to mock/stub for test purposes).

Mateusz W
  • 1,981
  • 1
  • 14
  • 16
2

Take a look at this link, it is possible to override constructors. However, I believe this is now what you want, you want to EXTEND it. Take a look at the "Extends ABC" part.

Soph
  • 2,895
  • 5
  • 37
  • 68