扩展Object.prototype JavaScript [英] Extending Object.prototype JavaScript
问题描述
我不是在问这是否合适:
Object.prototype.method = function(){};
这几乎被所有人认为是邪恶,考虑到它搞砸了 for(var i in obj)
。
真实问题
忽略
- 不称职的浏览器(不支持的浏览器
Object.defineProperty
) - 财产碰撞或覆盖的可能性
假设你有一些令人难以置信有用的方法,这被认为是错误的/不道德的吗?
Object.defineProperty(Object.prototype,'methodOnSteriods', {
value:function(){/ *制作早餐,解决世界和平,取出垃圾* /},
可写:true,
可配置:true,
enumerable:false
});
如果您认为上述内容是不道德的,为什么他们甚至会首先实现该功能?
我认为如果它适用于你的目标环境就好了。
<另外我认为原型扩展偏执狂被夸大了。只要您使用
hasOwnProperty()
就像一个优秀的开发人员一样,这一切都很好。最糟糕的情况是,您在其他地方重载该属性并丢失该方法。但如果你这样做,那就是你自己的错。 I am not asking if this is okay:
Object.prototype.method = function(){};
This is deemed evil by pretty much everyone, considering it messes up for(var i in obj)
.
The Real Question
Ignoring
- Incompetent browsers(browsers that don't support
Object.defineProperty
) - Potential for property collision or overriding
Assuming you have some incredibly useful method, is this considered wrong/unethical?
Object.defineProperty(Object.prototype, 'methodOnSteriods',{
value: function(){ /* Makes breakfast, solves world peace, takes out trash */ },
writable: true,
configurable: true,
enumerable: false
});
If you believe the above is unethical, why would they even implement the feature in the first place?
I think it's fine if it works in your target environment.
Also I think prototype extension paranoia is overblown. As long as you use hasOwnProperty()
like a good developer that it's all fine. Worst case, you overload that property elsewhere and lose the method. But that's your own fault if you do that.
这篇关于扩展Object.prototype JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!