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

前端 未结 5 2180
小鲜肉
小鲜肉 2020-11-28 10:20

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

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 11:10

    How to do simple classical inheritance in Javascript:

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

    How to override functions:

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

    The override function is created like this:

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

    Works with multiple arguments.
    Fails when trying to override undefined or nonfunctions.
    Makes "superFunction" a "reserved" word :-)

提交回复
热议问题