Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override image constructor in JS?

Tags:

javascript

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?

like image 227
Fluffy Avatar asked Jan 18 '23 21:01

Fluffy


2 Answers

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).

like image 73
Mateusz W Avatar answered Jan 29 '23 03:01

Mateusz W


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.

like image 38
Soph Avatar answered Jan 29 '23 03:01

Soph