Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding custom functions into 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(){    ... } 

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

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?

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

like image 286
mati Avatar asked Jun 04 '09 02:06

mati


People also ask

Can you add custom function to JS array prototype?

While the potential for clashing with other bits o' code the override a function on a prototype is still a risk, if you want to do this with modern versions of JavaScript, you can use the Object. defineProperty method, e.g.

How do you add a function to an array?

Create an ArrayList with the original array, using asList() method. Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.


1 Answers

While the potential for clashing with other bits o' code the override a function on a prototype is still a risk, if you want to do this with modern versions of JavaScript, you can use the Object.defineProperty method, turning off the enumerable bit, e.g.

// functional sort Object.defineProperty(Array.prototype, 'sortf', {     value: function(compare) { return [].concat(this).sort(compare); } }); 
like image 77
csells Avatar answered Oct 18 '22 09:10

csells