[英]If [] is [] and Array.prototype is [] why doesn't ([] == Array.prototype)
[英]Why can't I overwrite the prototype of `Array` (`Array.prototype`)?
我將Array
的原型設置為my
一個實例,我認為book.aa
將顯示"aa"
,但它顯示"undefined"
,為什么? 謝謝!
<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>
您無法分配給Array.prototype
因為prototype
是Array
的只讀屬性。
所以當你寫作
Array.prototype = new my();
什么都沒發生。 要了解原因,請嘗試
JSON.stringify(Object.getOwnPropertyDescriptor(Array, "prototype"))
結果是
"{"value":[],"writable":false,"enumerable":false,"configurable":false}"
除非您處於嚴格模式,否則分配將無效。
這就是原因 - 並且看看http://jsfiddle.net/5Ysub/ - 如果你執行
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);
你得到
undefinedbb
bb
有效,因為您在創建和設置bb
屬性時已分配給實際的 Array.prototype
。
恕我直言,不能打擊Array.prototype
是一件好事。 :)
即使你可以像這樣直接覆蓋Array.prototype,你也會失去對所有內置方法的訪問權限,例如splice,slice,push,shift,pop,unshift,sort,reverse等等......所以它會是可怕的編碼實踐。 但它不像雷指出的那樣有效,因為它是只讀的。
這個微小的代碼片段將證明無法覆蓋Array.prototype,因為sort
方法仍將執行:
<script type="text/javascript">
Array.prototype={};
var a=new Array(1,4,5,7,8);
a.sort();
alert(a.join(","));
</script>
如果要覆蓋Array.prototype的原型屬性,則必須一次執行一次,如下所示: Array.prototype.aa='aa';
如果要將大量屬性應用於Array.prototype,請通過循環應用它。 以下是我為您編寫的一些代碼,它們應該完全符合您的要求:
<script type="text/javascript">
function my()
{
this.aa = 'aa';
}
my.prototype.bb = "bb";
var instance = new my();
for(var j in instance)
{
if(instance.hasOwnProperty(j) || j in my.prototype)
{
Array.prototype[j]=instance[j];
}
}
var book=new Array();
book[0]="War and Peace";
alert(book.aa);//alerts "aa"
alert(book.bb);//alerts "bb"
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.