覆盖功能(例如“警报”)并调用原始功能? [英] Override function (e.g. "alert") and call the original function?

查看:107
本文介绍了覆盖功能(例如“警报”)并调用原始功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个调用原始版本的新版本覆盖Javascript内置函数(类似于在一个类上覆盖一个方法,其版本调用 super 在许多语言中)。我该怎么做?

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 super in many languages). How can I do this?

例如......

window.alert = function(str) {
    //do something additional
    if(console) console.log(str);

    //super.alert(str) // How do I do this bit?
}


推荐答案

存储对原始文件的引用变量中的函数:

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
    };
})();

通用方法是 < original_func_reference> .apply(this,arguments) - 保留上下文并传递所有论点。通常,也应该返回原始方法的返回值。

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

但是,已知 alert 是一个void函数,只接受一个参数,并且不使用这个对象。因此,在这种情况下, _alert(str)就足够了。

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.

注意:IE< = 8会引发错误如果你试图覆盖 alert ,那么请确保你使用的是 window.alert = ... 而不是 alert = ...

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

这篇关于覆盖功能(例如“警报”)并调用原始功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆