Override image constructor in JS?

后端 未结 2 530
轮回少年
轮回少年 2021-01-19 11:05

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 cons

2条回答
  •  旧时难觅i
    2021-01-19 11:30

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

提交回复
热议问题