Can you add a function to the captured JavaScript array?

This question is related to What are the best practices for declaring an array in Javascript?


Let's say the client, call them "DB Cooper" , has the first requirement that the following code must be executed before any other JavaScript code:

Array = function(){ alert('Mwahahahaha'); }; 

In addition, Cooper requires custom functions to be added to the built-in Array object (and not to the captured one). For example, if Array was hacked, this will be done with:

 Array.prototype.coolCustomFunction = function(){ alert('I have ' + this.length + ' elements! Cool!'); }; 

That will allow:

 var myArray = []; myArray.coolCustomFunction(); 

However, this is incompatible with the first requirement. Thus, how can you best meet both requirements of DB Cooper?

Note: DB even wrote a test script to help decide if it meets his requirements ... what a guy!


Update: For those of you who love the challenge: try finding an awkward cross-browser solution to this problem. For example, here is an even more restrained test case (thanks for reformatting this Berga) that captures Array, Object, Array.prototype.constructor and Object.prototype.constructor. It still looks like there might be a specific browser solution for this (see Bergi to comment on his answer , and let us know if you find a way to steal it in FF), but it’s not yet clear if there is a cross-browser solution for this.

+6
source share
3 answers

Regardless of your Array function / constructor, the literal syntax for arrays will always generate β€œreal” arrays with the [[prototype]] prototype object of its own array set (this was a security vulnerability once). That way you can always access this using

 Object.getPrototypeOf([]) 

even if an Array or [].constructor captured. (It will certainly not work when the Object is captured, then it will become really complex)

( Bued DB down! )


If you want to use a workaround in FF , the following line will always work (and not be captured):

 [].__proto__.coolCustomFunction = coolCustomFunction; 
+2
source

Since Array not necessarily [].constructor , you can use [].constructor to refer to the original Array function, since it is difficult, and Array = function(){} will not change it.

 Array = function () { alert("foo")}; // this will always point to the original Array [].constructor.prototype.foo = "bar"; var myArray = [0, 1]; alert(myArray.foo) // alerts "bar" 

http://jsfiddle.net/yXPJ8/5/

+3
source

Yes ... you just did ... but you created an array using [] .. if you use new Array() , it works fine ...

See an example here.

+1
source

Source: https://habr.com/ru/post/920707/


All Articles