0

I am working on react app. There is problem that some third party libraries extend the Array.prototype . They add extra properties to Array.prototype.

So, In my code whenever I define

var myArray = [];
console.log(myArray);  // those extended coming with it. 

How should I avoid this.

One way I tried using this way:

function myArray()
{
   this.array = new Array();
   return this.array;
}
var myArray = myArray(); //but no luck :(
AsgarAli
  • 2,201
  • 1
  • 20
  • 32
NeiL
  • 791
  • 8
  • 35
  • 2
    Using an IFrame this post show how to grab the default constructor. -> http://stackoverflow.com/questions/13990187/create-a-reset-of-javascript-array-prototype-when-array-prototype-has-been-modif – Keith Nov 03 '16 at 09:40
  • You should [fix](http://stackoverflow.com/q/13296340/1048572) the third party script instead. You even can make those methods non-enumerable after the fact. – Bergi Nov 07 '16 at 14:13
  • @Bergi Yes i followed this. It almost fixed most of the issue. Problem is It is also messing the code of other libraries i am using. For example , My app is written in ReactJS. I am using React Intl for language support. React Intl is not behaving correctly. And i have no control over that code also . If i try to put some hack in React Intl library. It is messing up the default behaviour. I was thinking to replace polluted Array.prototype with fresh one .Unfortuantely coudnt find the workaround. Below answer's method is just fine. It is not 100%. So cant use in production. – NeiL Nov 15 '16 at 06:49

1 Answers1

0
// code extending Array.prototype
Array.prototype.log = function(){
  console.log( this );
};

// code extracting the native Array from an iframe
var MyArray = getNativeArray();

function getNativeArray(){

  var iframe = document.createElement("iframe");
  iframe.src = "about:blank";
  document.body.appendChild(iframe);
  var native = iframe.contentWindow.Array;
  document.body.removeChild(iframe);
  return native;

}

// usage and comparison
var array1 = new Array(1,2,3);
var array2 = new MyArray(1,2,3);

console.log( array1 );                  // [1,2,3]
console.log( array2 );                  // [1,2,3]
console.log( typeof array1.log );       // "function"
console.log( typeof array2.log );       // "undefined"
console.log( array1 instanceof Array ); // true
console.log( array2 instanceof Array ); // false
console.log( Array.isArray(array1) );   // true
console.log( Array.isArray(array2) );   // true
pishpish
  • 2,574
  • 15
  • 22