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.prototypebecauseprototypeis a read-only property ofArray.So when you write
nothing happens. To see why, try
The result is
Unless you are in strict mode, the assignment silently fails.
That’s why — and see http://jsfiddle.net/5Ysub/ — if you execute
You get
The
bbworks because you have assigned to the realArray.prototypewhen you created and set thebbproperty.It is a good thing that
Array.prototypecannot be whacked, IMHO. 🙂