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>
                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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With