为什么重新分配Object.prototype不起作用? [英] Why is reassigning Object.prototype not working?

查看:61
本文介绍了为什么重新分配Object.prototype不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不起作用?

// this one works as I expected, when objSayHello()
Object.prototype.objSayHello = function(){alert('Hello,from OBJECT prototype')};
// NOT working !
Object.prototype ={objSayHello: function(){alert('Hello,from OBJECT prototype')}};

objSayHello();

推荐答案

  1. 因为您已经替换了Object原型,所以您要将objSayHello方法添加到任何从Object派生的对象(所有对象).

  1. Because you've replaced the Object prototype, so you're adding a objSayHello method to any object descending from Object (all objects).

请勿替换Object.prototype.

您可能想要的是:

someObj.prototype.objSayHello = function(){alert('Hello,from OBJECT prototype')};

然后通过以下方式调用它:

Then to call it with:

someObj.objSayHello();

您似乎打算做的是:

Object.prototype.objSayHello = function(){alert('Hello,from OBJECT prototype')};

但这可能不是一个好主意,因为如果处理不正确,它将与迭代器(for...in)冲突.

But that is probably a bad idea as it will conflict with iterators (for...in) if not handled correctly.

这篇关于为什么重新分配Object.prototype不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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