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

时间:2012-05-03 08:28:09

标签: javascript override

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

例如......

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

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

5 个答案:

答案 0 :(得分:43)

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

(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)就足够了。

注意:如果您尝试覆盖alert,则IE&lt; = 8会引发错误,因此请确保您使用window.alert = ...代替alert = ...

答案 1 :(得分:21)

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

注意“自调用函数”,它返回一个新的函数对象(分配给window.alert属性)。返回的新函数对象在变量 original周围创建一个闭包,该闭包计算为传递给“window.alert的{​​{1}}的原始自我调用功能“。

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

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

快乐的编码。

答案 2 :(得分:5)

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

这就是你要做的:

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

答案 3 :(得分:2)

如何在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”成为“保留”字: - )

答案 4 :(得分:1)

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

相关问题