簡體   English   中英

覆蓋函數(例如“警報”)並調用原始函數?

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

我想用調用原始版本的新版本覆蓋 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)在這種情況下就足夠了。

注意:如果您嘗試覆蓋alert ,IE <= 8 會引發錯誤,因此請確保您使用的是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)
}})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM