添加自定义功能于Array.prototype [英] adding custom functions into Array.prototype

查看:197
本文介绍了添加自定义功能于Array.prototype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的支持AJAX的asp.net应用程序。
我只是增加了一些方法应用到Array.prototype像

I was working on an AJAX-enabled asp.net application. I've just added some methods to Array.prototype like

Array.prototype.doSomething = function(){
                                         ...
                                          }

这个解决方案在一个'pretty'的方式工作对我来说,是可能的重用code。

This solution worked for me, being possible reuse code in a 'pretty' way.

但是,当我测试过它与整个页面的工作,我有问题..
我们有一些自定义的AJAX扩展,并且他们开始表现为突发:某些控件显示的未定义围绕其内容或价值

But when I've tested it working with the entire page, I had problems.. We had some custom ajax extenders, and they started to behave as the unexpected: some controls displayed 'undefined' around its content or value.

有什么能为事业?我失去了一些关于对矫正对象非标准的原型?

What could be the cause for that? Am I missing something about modifing the prototype of standart objects?

请注意:我是pretty确认错误,当我修改原型阵列开始。它应该是只兼容IE。

Note: I'm pretty sure that the error begins when I modify the prototype for Array. It should be only compatible with IE.

推荐答案

修改内置对象的原型可以在一般一个坏主意,因为它总是与其他code发生冲突在同一页上的潜力

Modifying the built-in object prototypes can be a bad idea in general, because it always has the potential to clash with other code on the same page.

在Array对象原型的情况下,这是一个特别糟糕的主意,因为它与任何一件code的干扰的潜力迭代任何数组成员,例如用对。在

In the case of the Array object prototype, it is an especially bad idea, because it has the potential to interfere with any piece of code that iterates over the members of any array, for instance with for .. in.

要说明使用一个例子(从<借来的href=\"http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays/500531#500531\">here):

To illustrate using an example (borrowed from here):

Array.prototype.foo = 1;

// somewhere deep in other javascript code...
var a = [1,2,3,4,5];
for (x in a){
    // Now foo is a part of EVERY array and 
    // will show up here as a value of 'x'
}

这将是更好地为您创建自己的类型的对象构造完整的DoSomething的功能,而不是扩展内置阵列。

It would be better for you to create your own type of object constructor complete with doSomething function, rather than extending the built-in Array.

这篇关于添加自定义功能于Array.prototype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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