0

I just read the John Resig article about overriding the globals in browser (e.g. Array) but when I try that example in my browser, nothing happend.

Here the code:

var sec = {};
function Array() { 
    alert(1); 
    sec = this; 
}; 

and when I run ["zdxc", "sd", 1111, 11.1] in my browser's console, nothing happend. Array declared and no alert shown.

Is that a bug that fixed in modern browsers or it's still works in some version of browsers?

Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201

1 Answers1

2

Thats because you override the Array-contructor which makes the call new Array(); return your custom object insted of an actual Array.

So calling

var arr = ["zdxc", "sd", 1111, 11.1];

makes arr beeing a native Array.

Calling

var arr_override = new Array();

makes arr_override beeing an Object of the type you declared before and therefore executing your alert-statement. Overriding the constructor kind of "erases" the Array-initialisation from the identifier replacing it with your constructor function. Its not an actual Array.

According to the answer to this question the Array-Literal ([]) is not beeing affected by this behaviour since about 2008 in all mayor browsers..

EDIT:

After trying around a bit it does not seem to be possible to modify the behaviour of the []-notation and it is not recomended either to modify Native Objects (expecially their constructors) at all btw.

How ever it is possible to extend the prototypes and also to modify existing properties/methods like in the example below

var arr = [];
arr.push('2323');
alert(arr);

Array.prototype.push = function() { alert('trololololo'); }
arr.push(123);

Hope this helps. Cheers!

Community
  • 1
  • 1
nozzleman
  • 9,529
  • 4
  • 37
  • 58