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?
Asked
Active
Viewed 1,482 times
4

Fluffy
- 27,504
- 41
- 151
- 234
2 Answers
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
-
This worked in FF, only thing I'd add is that the Image object can take in an optional width and height parameter. – patorjk Jan 03 '12 at 19:17
-
Updated to provide width and height :) – Mateusz W Jan 03 '12 at 19:21