为什么我不能覆盖`Array`(Array.prototype`)的原型? [英] Why can't I overwrite the prototype of `Array` (`Array.prototype`)?

查看:41
本文介绍了为什么我不能覆盖`Array`(Array.prototype`)的原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Array 的原型设置为 my 的实例,我认为 book.aa 将显示"aa" ,但显示"undefined" ,为什么?谢谢!

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>

推荐答案

您无法分配给 Array.prototype ,因为 prototype 的只读属性数组.

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

所以当你写

Array.prototype = new my();

什么都没有发生.要了解原因,请尝试

nothing happens. To see why, try

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

结果是

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

除非您处于严格模式,否则分配将自动失败.

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

这就是原因-如果执行,请参阅 http://jsfiddle.net/5Ysub/

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);

你得到

undefinedbb

bb 之所以有效,是因为您在创建并设置 bb real Array.prototype >属性.

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

恕我直言,不能对 Array.prototype 进行黑客攻击是一件好事.:)

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

这篇关于为什么我不能覆盖`Array`(Array.prototype`)的原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆