问题描述
在JavaScript的本机类型(如Array,String,Number等)中构建其他功能原型是不是一个坏主意?
Is it a bad idea to prototype additional features in JavaScript's native types like Array, String, Number, etc?
我认为拥有类似的功能会很棒myArr.pop()等等,但如果有一天成为ECMAScript x的一部分 - 并且与我的实现不同,那么,它可能会破坏整个软件吗?
I think it would be great to have functionality like myArr.pop(), etc., but what if someday that becomes part of the ECMAScript x -- and differs from my implementation, so, it potentially breaks the entire software?
推荐答案
Prototype是一个广泛扩展本机Javascript类型和DOM类的库,并且非常好地展示了扩展Javascript本机类型的好,坏和丑陋。
Prototype is a library that extensively extends native Javascript types and DOM classes, and shows extremely well the good, the bad and the ugly of extending Javascript native types.
好:你得到看起来很自然的Javascript代码。
The Good: You get natural-looking Javascript code.
坏:你忘了你实际上在使用Prototype - 产生混乱时切换到不使用Prototype的项目。 (为什么我不能......哦,对,这是一个Prototype功能。)
The Bad: You forget that you are actually using Prototype - spawning confusion when you switch to a project that does not use Prototype. (Why can't I... oh, right, that was a Prototype capability.)
丑陋:如果方法定义存在冲突(两种方法,由于库,浏览器或规范存在冲突,您可能必须修改客户端代码以保持兼容性,因此在合同或签名方面存在差异。这使得在一个已经困扰它们的世界中需要考虑更多兼容性。
The Ugly: If there is a conflict for method definitions (two methods that differ in either contracts or signatures) because of conflicting libraries, the browser or the specification, you may have to modify client code to maintain compatibility. Which makes one more compatibility consideration to make in a world already plagued with them.
为了兼容性并保持我自己的想法清晰,我个人不要扩展原生或DOM javascript类型,并且喜欢较少侵入的库到Prototype。
For the sake of compatibility and keeping my own ideas clear, I personally refrain from extending native or DOM javascript types, and prefer less intrusive libraries to Prototype.
但是,如果你对这些缺点感到放心,不要让我阻止你。
However, if you feel at ease with these drawbacks, don't let me stop you.
这篇关于不鼓励原型JavaScript本机类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!