0

I need to override a method of a specific array, not every array, just one object, and it need to work just like a normal array, something like that:

var arr1 = [];
var arr2 = [];

overrideThatWay(arr1);

arr1.push(2); //invoke overrided method
arr2.push(2); //invoke regular method

for(var a1 in arr1){
//act like an array, dont list the overrided methods
}
melanke
  • 804
  • 1
  • 9
  • 25

2 Answers2

1
arr1.push = function (item) {
// "overloaded" function
}
Francis Avila
  • 31,233
  • 6
  • 58
  • 96
  • but it will be listed in the for loop :/ – melanke Jun 11 '12 at 17:28
  • @melanke: That's because you're using the wrong type of loop. If you only want numeric indices, you should be using a `for` statement. The `for-in` statement is a poor fit for index based iteration in JavaScript. –  Jun 11 '12 at 17:43
  • alright, but I want be able to use that anyway, because it is an API and I want to keep this compatibility – melanke Jun 11 '12 at 18:02
  • Your API is wrong. Do not use `for .. in array` to iterate an array. This is not a "compatibility" you should keep. – Francis Avila Jun 11 '12 at 18:32
0

maybe this way, but i dont know the implications:

Object.defineProperty(arr1, "push", {
          enumerable: false
        , configurable: true
        , writable: false
        , value: function(prop) {
                    //do something
                }

});
melanke
  • 804
  • 1
  • 9
  • 25