重新审视在ECMAScript 5之后扩展原生原型 [英] Revisiting extending native prototypes after ECMAScript 5

查看:141
本文介绍了重新审视在ECMAScript 5之后扩展原生原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,鉴于对ECMAScript 5中定义属性的更改,我重新讨论了是否可以安全地扩展本机JavaScript原型的问题。事实上,我一直在扩展像Array和Function这样的原型,但出于显而易见的原因,我避免使用Object。在使用Jasmine的单元测试中,通过将Object.prototype规范添加到我自己的个人框架的规范中,使用不可枚举的函数扩展Object.prototype似乎是安全的。但是,像type属性这样的数据属性,使用任何异常处理的getter / setter都会产生意想不到的后果。仍然存在与其他图书馆发生冲突的可能性 - 尽管在我的工作中,几乎没有出现过。然而,只要函数不可枚举,看起来扩展Object.prototype就可以是安全的。



您怎么看?现在扩展Object.prototype是否安全?请讨论。

解决方案

将原生对象扩展到JavaScript可能会变得更安全,因为许多碰撞问题仍然存在。一般来说,除非你从最近的标准扩展对象以支持标准化行为,否则引入包装器仍然会更加安全 - 当你是唯一受控制的人时,更容易正确地做事。



说到环境原生的对象(DOM元素和节点,AJAX的东西),新的JS标准仍然没有给出,并且可以说,不能给出除了在其界面标准中定义的内容之外,您可以保证与之交互。永远不要忘记它们可能通过许多不同的脚本引擎访问,因此不需要针对某种特定语言的怪癖进行定制 - JS。因此,建议不要延长它们。或者

Recently, given the changes to defining properties in ECMAScript 5, I have revisited the question of whether we can safely extend the native JavaScript prototypes. In truth, all along I have extended prototypes like Array and Function, but I avoided doing so with Object, for the obvious reasons. In unit testing with Jasmine, by adding Object.prototype specs to specs for my own personal framework, extending Object.prototype with non-enumerable functions has appeared to be safe. Data properties like a "type" property, however, with getters/setters that do any unusual processing have had unintended consequences. There is still the possibility of conflicts with other libraries--though in my work, that hardly ever comes up. Nevertheless, as long as the functions are not enumerable, it looks like extending Object.prototype can be safe.

What do you think? Is it safe to extend Object.prototype now? Please discuss.

解决方案

Extending objects native to JavaScript might become a little safer, through many collision concerns still stand. Generally, unless you're extending object to support standartized behavior from more recent standard it really would be still much safer to introduce wrapper - it is much easier to do things right way when you're the only one in control.

Speaking of objects native to environment (DOM elements and nodes, AJAX stuff), new JS standard still don't give and, arguably, can't give you any guarantee about any interaction with those except what defined in their interface standard. Never forget that they're potentially accessible through many different scripting engines and thus not need to be tailored for quirks of one specific language - JS. So recommendation to not extend those either still stands as well.

这篇关于重新审视在ECMAScript 5之后扩展原生原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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