adding custom functions into Array.prototype

JavascriptArraysInternet Explorer

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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); }
});

Solution 2 - Javascript

Modifying the built-in object prototypes is a bad idea in general, because it always has the potential to clash with code from other vendors or libraries that loads on the same page.

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.

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'
}

Unfortunately, the existence of questionable code that does this has made it necessary to also avoid using plain for..in for array iteration, at least if you want maximum portability, just to guard against cases where some other nuisance code has modified the Array prototype. So you really need to do both: you should avoid plain for..in in case some n00b has modified the Array prototype, and you should avoid modifying the Array prototype so you don't mess up any code that uses plain for..in to iterate over arrays.

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.

What about Object.defineProperty?

There now exists Object.defineProperty as a general way of extending object prototypes without the new properties being enumerable, though this still doesn't justify extending the built-in types, because even besides for..in there is still the potential for conflicts with other scripts. Consider someone using two Javascript frameworks that both try to extend the Array in a similar way and pick the same method name. Or, consider someone forking your code and then putting both the original and forked versions on the same page. Will the custom enhancements to the Array object still work?

This is the reality with Javascript, and why you should avoid modifying the prototypes of built-in types, even with Object.defineProperty. Define your own types with your own constructors.

Solution 3 - Javascript

There is a caution! Maybe you did that: fiddle demo

Let us say an array and a method foo which return first element:

var myArray = ["apple","ball","cat"];

foo(myArray) // <- 'apple'

function foo(array){
    return array[0]
}

The above is okay because the functions are uplifted to the top during interpretation time.

But, this DOES NOT work: (Because the prototype is not definned)

myArray.foo() // <- 'undefined function foo'

Array.prototype.foo = function(){
    return this[0]
}

For this to work, simply define prototypes at the top:

Array.prototype.foo = function(){
    return this[0]
}

myArray.foo() // <- 'apple'

> And YES! You can override prototypes!!! It is ALLOWED. You can even define your own own add method for Arrays.

Solution 4 - Javascript

You augmented generic types so to speak. You've probably overwritten some other lib's functionality and that's why it stopped working.

Suppose that some lib you're using extends Array with function Array.remove(). After the lib has loaded, you also add remove() to Array's prototype but with your own functionality. When lib will call your function it will probably work in a different way as expected and break it's execution... That's what's happening here.

Solution 5 - Javascript

Using Recursion

function forEachWithBreak(someArray, fn){
   let breakFlag = false
   function breakFn(){
       breakFlag = true
   }
   function loop(indexIntoSomeArray){
    
       if(!breakFlag && indexIntoSomeArray<someArray.length){
           fn(someArray[indexIntoSomeArray],breakFn)
           loop(indexIntoSomeArray+1)   
       }
   }
   loop(0)
}

Test 1 ... break is not called

forEachWithBreak(["a","b","c","d","e","f","g"], function(element, breakFn){
    console.log(element)
})

Produces a b c d e f g

Test 2 ... break is called after element c

forEachWithBreak(["a","b","c","d","e","f","g"], function(element, breakFn){
    console.log(element)
    if(element =="c"){breakFn()}
})

Produces a b c

Solution 6 - Javascript

There are 2 problems (as mentioned above)

  1. It's enumerable (i.e. will be seen in for .. in)
  2. Potential clashes (js, yourself, third party, etc.)

To solve these 2 problems we will:

  1. Use Object.defineProperty
  2. Give a unique id for our methods
const arrayMethods = {
    doSomething: "uuid() - a real function"
}

Object.defineProperty(Array.prototype, arrayMethods.doSomething, {
    value() {
        // Your code, log as an example
        this.forEach(v => console.log(v))
    }
})

const arr = [1, 2, 3]
arr[arrayMethods.doSomething]() // 1, 2, 3

The syntax is a bit weird but it's nice if you want to chain methods (just don't forget to return this):

arr
    .map(x=>x+1)
    [arrayMethods.log]()
    .map(x=>x+1)
    [arrayMethods.log]()

Solution 7 - Javascript

In general messing with the core javascript objects is a bad idea. You never know what any third party libraries might be expecting and changing the core objects in javascript changes them for everything.

If you use Prototype it's especially bad because prototype messes with the global scope as well and it's hard to tell if you are going to collide or not. Actually modifying core parts of any language is usually a bad idea even in javascript.

(lisp might be the small exception there)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmatiView Question on Stackoverflow
Solution 1 - JavascriptcsellsView Answer on Stackoverflow
Solution 2 - JavascriptthomasrutterView Answer on Stackoverflow
Solution 3 - JavascripttikaView Answer on Stackoverflow
Solution 4 - JavascriptRobert KoritnikView Answer on Stackoverflow
Solution 5 - JavascriptgrabbagView Answer on Stackoverflow
Solution 6 - JavascriptEdan ChetritView Answer on Stackoverflow
Solution 7 - JavascriptJeremy WallView Answer on Stackoverflow