![](/img/trans.png)
[英]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.