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

前端 未结 5 2181
小鲜肉
小鲜肉 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条回答
  •  猫巷女王i
    2020-11-28 11:07

    I'm assuming your question is how do you overwrite a built-in and still be able to call it. First off as a disclaimer, you should never overwrite built ins unless you have a good reason for doing it since it will make it impossible to debug/test.

    This is how you would do it:

    window._alert = window.alert;
    window.alert = function(str) { 
         if(console) console.log(str);
         window._alert(str);
    }
    

提交回复
热议问题