在Javascript中向Object.prototype添加方法有什么好处和危险? [英] What are the benefits and dangers of adding methods to Object.prototype in Javascript?
问题描述
我知道五年前这是一个有争议的问题,但我想知道今天的JavaScript是否有所改变。是否有任何现实世界的主要现代图书馆与扩展 Object.prototype
不兼容的例子?
我是对假设的有人可能会在你想要使用的库中的迭代代码中编写错误的感兴趣,可能在将来,然后你可能会得到一个奇怪的错误
是否存在与扩展Object.prototype不兼容的主要现代库的真实示例?
是的,我记得jQuery的问题,这是较少侵入性的库之一例如:
我记得的另一个案例是有人添加了加载
函数t o Object.prototype
对象,它导致 $()。load
事件出现问题:
//不要这样做! :)
Object.prototype.load = function(){};
$(窗口).load(function(){
alert('load event'); //从不解雇
});
示例此处。
永远不建议以这种方式扩充 Object.prototype
对象,因为这些属性将是由大量对象继承 - 即使是某些宿主对象 - 并且如您所知,主要关注的是它们将由 for-in
语句枚举。
在ECMAScript 5中,现在存在一种更安全的方式,因为我们现在可以声明不可枚举的属性,例如:
Object.defineProperty(Object.prototype,'foo',{value:'bar'});
在属性描述符中 - {value:'bar'}
- 我们可以指定属性属性,对于 Value Properties ,如上例所示,我们可以指定可写
属性,和公共可配置
属性(确定是否可以重新配置属性 - 属性更改 - 或删除。
我们还有可枚举
属性,该属性确定该属性是否将由 for-in
语句枚举。 / p>
如果我们没有指定属性,它们是 false
默认情况下,描述符将如下所示: p>
{
value:'bar',
可写:false,
可配置:false,
可枚举:false
}
I know this was a contentious issue five years ago, but I'm wondering if things have changed for today's JavaScript. Are there any real world examples of a major modern library being incompatible with extending Object.prototype
?
I'm not interested in hypothetical "someone may write bad for in
iteration code in a library that you want to use, maybe, in the future, and then you might get a weird bug"
Are there any real world examples of a major modern library being incompatible with extending Object.prototype?
Yes, I remember problems with jQuery, -which is one of the less intrusive libraries- for example:
Another case that I remember is that someone added a load
function to the Object.prototype
object, and it caused problems with the $().load
event:
// DON'T DO THIS ! :)
Object.prototype.load = function () {};
$(window).load(function () {
alert('load event'); // never fired
});
Example here.
Augmenting the Object.prototype
object in that way is never recommended, because those properties will be inherited by a great number of objects -even also by some host objects-, and as you know, the primary concern is that they will be enumerated by the for-in
statement.
In ECMAScript 5, now a safer way exist, because we can now declare non-enumerable properties, for example:
Object.defineProperty(Object.prototype, 'foo', { value: 'bar' });
In the property descriptor -{ value: 'bar' }
- we can specify property attributes, in the case of Value Properties as in the above example, we can specify the writable
attribute, and the common configurable
attribute (determines if a property can be re-configured -attribute changes- or deleted.
And we have also the enumerable
attribute, which determines if the property will be enumerated by the for-in
statement.
If we don't specify the attributes, they are false
by default, the descriptor will look like:
{
value: 'bar',
writable: false,
configurable: false,
enumerable: false
}
这篇关于在Javascript中向Object.prototype添加方法有什么好处和危险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!