Override function (e.g. “alert”) and call the original function?

前端 未结 5 2167
小鲜肉
小鲜肉 2020-11-28 10:20

I would like to override a Javascript built-in function with a new version that calls the original (similarly to overriding a method on a class with a version that calls

5条回答
  •  一整个雨季
    2020-11-28 10:59

    Store a reference to the original function in a variable:

    (function() {
        var _alert = window.alert;                   // <-- Reference
        window.alert = function(str) {
            // do something additional
            if(console) console.log(str);
            //return _alert.apply(this, arguments);  // <-- The universal method
            _alert(str);                             // Suits for this case
        };
    })();
    

    The universal way is .apply(this, arguments) - To preserve context and pass all arguments. Usually, the return value of the original method should also be returned.

    However, it's known that alert is a void function, takes only one argument, and does not use the this object. So, _alert(str) is sufficient in this case.

    Note: IE <= 8 throws an error if you try to overwrite alert, so make sure that you're using window.alert = ... instead of alert = ....

提交回复
热议问题