Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I overwrite the prototype of `Array` (`Array.prototype`)?

Tags:

javascript

I set the prototype of Array as an instance of my, I think book.aa will display "aa", but it displays "undefined", why? Thanks!

   <html>
    <head>
        <title>Array Properties</title>
        <h2>Array Properties</h2>
        <script type="text/javascript">
            function my() {
                this.aa = 'aa';
            }
            Array.prototype = new my();
            Array.prototype.bb = "bb";
            var book = new Array();  
            book[0] = "War and Peace";  

        </script>
    </head>
    <body bgcolor="lightblue">
        <script type="text/javascript">
            document.write(book.aa+book.bb);
        </script>
    </body>

    </html>
like image 817
HelloCW Avatar asked Oct 10 '12 02:10

HelloCW


1 Answers

You cannot assign to Array.prototype because prototype is a read-only property of Array.

So when you write

Array.prototype = new my();

nothing happens. To see why, try

JSON.stringify(Object.getOwnPropertyDescriptor(Array, "prototype"))

The result is

"{"value":[],"writable":false,"enumerable":false,"configurable":false}"

Unless you are in strict mode, the assignment silently fails.

That's why -- and see http://jsfiddle.net/5Ysub/ -- if you execute

function my() {
    this.aa = 'aa';
}
Array.prototype = new my();
Array.prototype.bb = "bb";
var book = new Array();
book[0] = "War and Peace";
document.write(book.aa+book.bb);

You get

undefinedbb

The bb works because you have assigned to the real Array.prototype when you created and set the bb property.

It is a good thing that Array.prototype cannot be whacked, IMHO. :)

like image 159
Ray Toal Avatar answered Oct 27 '22 00:10

Ray Toal