0

Someone asked me a trick question and I'm not sure how to do it. I'll appreciate any help.

Question: When you call Array.push(), it should push as normal and should also make a call to custom function.

Here is my attempt:

Array.prototype.push = function() {
  Array.prototype.push.call(this, arguments);
  if(typeof customMethod === 'function') {
    customMethod();
  }
} 

function customMethod() { 
  console.log('customMethod called');
}

But this doesn't work.

JS-JMS-WEB
  • 2,555
  • 3
  • 17
  • 26

3 Answers3

2

You need to make a backup of the original implementation, and call that, otherwise you'll get into infinite recursion.

Array.prototype._old_push = Array.prototype.push;
Array.prototype.push = function() {
    Array.prototype._old_push.call(this, arguments);
    if(typeof customMethod === 'function') {
        customMethod();
    }
} 
Cristik
  • 30,989
  • 25
  • 91
  • 127
2

It won't work because you are referencing the same method, and causing a recursion. You'll have to store the original "super" method, then override it to achieve the desired affect.

Here is how it would work:

Array.prototype._push = Array.prototype.push;

Array.prototype.push = function() {
  this._push.apply(this, arguments);

  if(typeof customMethod === 'function') {
    customMethod();
  }
};

function customMethod() {
  console.log('called custom method');
}

var a = [];

a.push(1);
a.push(2);

console.log(a);
Or Barmatz
  • 307
  • 3
  • 8
0

You shouldn't modify prototype of push because you are going to break every external libraries.

But if you need to do that you can save the old push and reuse it.

Array.prototype._oldPush = Array.prototype.push;
Array.prototype.push = function() {
  Array.prototype._oldPush.call(this, arguments);
  if(typeof customMethod === 'function') {
    customMethod();
  }
} 

Instead of doing this, try to use external method that do the stuff.

function CustomPush(array, datas) {
   Array.prototype.push.call(array, datas);
   if(typeof customMethod === 'function') {
       customMethod();
   }
}
Arnaud Gueras
  • 2,014
  • 11
  • 14