覆盖功能(例如"警报")并调用原始功能?

23 javascript overriding

我想用一个调用原始版本的新版本覆盖一个Javascript内置函数(类似于用一个调用super多种语言版本的类重写一个方法).我怎样才能做到这一点?

例如...

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

    //super.alert(str) // How do I do this bit?
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 46

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

(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
    };
})();
Run Code Online (Sandbox Code Playgroud)

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

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

注意:如果您尝试覆盖alert,IE <= 8会引发错误,因此请确保使用window.alert = ...而不是alert = ....

  • 刚刚测试过:所有主流浏览器都允许修改全局`window.alert`,但IE <= 8除外.在IE 9之前,尝试覆盖`alert`时会抛出错误. (3认同)

小智 21

没有"超级".无论如何,创建一个闭包以"保持"原始函数对象.

请注意"自调用函数",它返回一个新的函数对象(分配给该window.alert属性).返回的新函数对象周围产生一个闭合变量 original,其计算结果为原始window.alert,在"自主调用功能"获得通过.

window.alert = (function (original) {
  return function (str) {
    //do something additional
    if(console) {
      console.log(str)
    }
    original(str)
  }
})(window.alert)
Run Code Online (Sandbox Code Playgroud)

但是,我相信一些浏览器可能会阻止alert和其他内置版本被修改...

快乐的编码.


Art*_*Art 5

我假设您的问题是如何覆盖内置并仍然可以调用它.首先作为免责声明,你绝不应该覆盖内置的ins,除非你有充分的理由这样做,因为它将无法进行调试/测试.

这是你怎么做的:

window._alert = window.alert;
window.alert = function(str) { 
     if(console) console.log(str);
     window._alert(str);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您仅设置 window._alert 未定义,则不会。 (3认同)
  • 注意:此方法不易扩展.两次调用相同的代码,你丢失了原始方法. (2认同)