Override image constructor in JS?

后端 未结 2 529
轮回少年
轮回少年 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条回答
  • 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).

    0 讨论(0)
  • 2021-01-19 11:50

    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.

    0 讨论(0)
提交回复
热议问题