Overriding array constructor in javascript

Let's say I have the following code:

var secrets; Array = function() { secrets = this; }; 

The author of the above example says that the code overrides the Array constructor. First off, I'm not sure what this means. Can anyone advise?

Secondly: will the following code be equivalent?

 var secrets; function Array() { secrets = this; } 

By the way, the above code is taken from the following article about the Json vulnerability: see here

+6
source share
2 answers

In both examples, you define the Array variable as a function that assigns this secrets . It so happened that there already exists a global object called Array , which another JS on the page may or may not use as a Constructor to create arrays. If you log into the console and reassign Array as something else, you can start getting errors from code that is explicitly dependent on Array . However, arrays made literally using [] continue to work fine, and in fact their __proto__ still indicates that it was Array.prototype . So:

 var arr1 = new Array('a','b','c'); // arr[0] -> 'a' var arr2 = ['d','e','f']; // arr[0] -> 'd' var secrets; Array = function() { secrets = this; }; var arr3 = new Array('g','h','i'); // nothing wrong here, because Array is a function // arr3[0] -> undefined // Array is just a function, you can't make arrays with new Array anymore // and arr3 is just a function var arr4 = ['j','k','l']; // arr4[0] -> 'j' // making array literals still works 

as for this , nothing strange, still follows the rules of this . the fact that you assign an Array function does not change the behavior of this . therefore, this points to a global object that is in the browser window , unless you create an instance using new or use call or apply

the difference between the two selections is the difference between a function expression and a function declaration, see What is the difference between a vs declaration function expression in Javascript?

+5
source

Yes, both fragments are equivalent. Both override the array constructor, trying to intercept all the array data used by the website where it was entered, as explained in a related article. The value of this must be a newly constructed array.

This seems to be allowed by ECMAScript 3, but prohibited by ECMAScript 5, now available for all modern browsers. Thus, the operation described in the article will no longer work.

+1
source

All Articles