覆盖函数(例如“alert”)并调用原始函数

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

本文关键字:函数 原始 调用 alert 例如 覆盖      更新时间:2023-09-26

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

例如。。。

window.alert = function(str) {
    //do something additional
    if(console) console.log(str);
    //super.alert(str) // How do I do this bit?
}

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

(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) - 保留上下文并传递所有参数。通常,还应返回原始方法的返回值。

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

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

没有"超级"。无论如何,创建一个闭包来"保留"原始函数对象。

请注意返回新函数对象(分配给 window.alert 属性)的"自调用函数"。返回的新函数对象在变量original周围创建一个闭包,该闭包的计算结果为传递给"自调用函数"的原始window.alert

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

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

快乐编码。

我假设您的问题是如何覆盖内置并仍然能够调用它。首先作为免责声明,除非你有充分的理由这样做,否则你永远不应该覆盖内置的,因为它会使调试/测试变得不可能。

这是您将如何做到这一点:

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

如何在 Javascript 中进行简单的经典继承:

SuperClass.call(this) // inherit from SuperClass (multiple inheritance yes)

如何覆盖函数:

this.myFunction = this.myFunction.override(
                    function(){
                      this.superFunction(); // call the overridden function
                    }
                  );

覆盖函数的创建方式如下:

Function.prototype.override = function(func)
{
 var superFunction = this;
 return function() 
 {
  this.superFunction = superFunction;
  return func.apply(this,arguments);
 };
};

适用于多个参数。
尝试覆盖未定义或非函数时失败。
使"superFunction"成为"保留"词:-)

JavaScript 不使用经典的继承模型。这里有一篇很好的文章,描述了一种编写类的方法,以便可以使用类似的语法,但它本身不受支持。

通过使用代理对象,您可以执行此操作。

window.alert = new Proxy(window.alert , {
apply: function(target,that,args){
    console && console.log(args.join(''n'));
    target.apply(that,args)
}})