How to extend Array.prototype.push()?

后端 未结 6 713
遥遥无期
遥遥无期 2020-11-27 02:45

I\'m trying to extend the Array.push method so that using push will trigger a callback method, then perform the normal array function.

I\'m not quite sure how to do

6条回答
  •  萌比男神i
    2020-11-27 03:32

    You could do it this way:

    arr = []
    arr.push = function(data) {
      alert(data); //callback
    
      return Array.prototype.push.call(this, data);
    }
    

    If you're in a situation without call, you could also go for this solution:

    arr.push = function(data) {
      alert(data); //callback
    
      //While unlikely, someone may be using psh to store something important
      //So we save it.
      var saved = this.psh;
      this.psh = Array.prototype.push;
      var ret = this.psh(data);
      this.psh = saved;
      return ret;
    }
    

    Edit:

    While I'm telling you how to do it, you might be better served with using a different method that performs the callback then just calls push on the array rather than overriding push. You may end up with some unexpected side effects. For instance, push appears to be varadic (takes a variable number of arguments, like printf), and using the above would break that.

    You'd need to do mess with _Arguments() and _ArgumentsLength() to properly override this function. I highly suggest against this route.

    Edit once more: Or you could use "arguments", that'd work too. Still advise against taking this route though.

提交回复
热议问题