How to modify the system default method JavaSrcipt

There are some ways the system very easy to use, but always felt there are some areas for improvement, and how we should modify the system method can, here to do a simple case, to help people understand.

alert method to modify the system, so the system while the pop-up in the console window and print

(function(window){
    let a = window.alert;
    function alert(text){
        console.log(text)
        a(text);
    }
    window.alert = alert;
})(window);
alert("test alert");
在上面的代码中,声明一个函数把window这个顶层的对象传了进去,之后再函数中声明一个变量a,
a被赋值获得了原来的系统alert方法。你可以理解为a现在就是原来那个alert了。
之后重新定义一个方法,我这里叫alert,你也可以叫做其他名字,只要最后重新赋值给window.alert就可以。
我在我定义的alert方法中把传入的参数打印了一下,就是console.log这个方法。之后再用刚声明的a来实现原来系统默认的alert方法输出下。
这里在我自己调试代码的时候方便一些。
在最后方法都设置好后,直接赋值给window.alert  。这样就做到了覆盖原来系统方法的目的。

这里是为大家介绍修改系统默认方法的方式,如果有其他修改也可以跟着这个思路去修改。

Guess you like

Origin www.cnblogs.com/caominjie/p/10960281.html
Recommended