How to extend Array.prototype.push()?

后端 未结 6 707
遥遥无期
遥遥无期 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条回答
  •  离开以前
    2020-11-27 03:32

    The question is old, but for those who'll find this question nowadays, there's another, more native method to achieve this: Proxy

    const target = [];
    
    const handler = {
      set: function(array, index, value) {
        // call callback function here
    
        // The default behavior to store the value
        array[index] = value;
    
        // Indicate success
        return true;
      }
    };
    
    const proxyArray = new Proxy(target, handler);
    

提交回复
热议问题