1

In some code I'm working on I created a JavaScript function that is applied solely to Arrays, and I thought I'd try adding it as a member function.

I added it like so:

Array.prototype.myfunc = function(a){
    ...
}

Which works fine for the most part. The problem I run into then is with a for-in loop. It includes that function in the loop. If I then type in this snippet:

var bar, foo = ['alpha', 'bravo', 'charlie'];
for(bar in foo) console.log(foo[bar]);

Then the output is along the lines of:

alpha
bravo
charlie
function myFunc(a){
    ...
}

So is there any way of doing this but avoiding it showing in the for-in loop?

Jacob Ewing
  • 770
  • 7
  • 22
  • 6
    You can use `Object.defineProperty` but as always, changing the prototype of global objects is *heavily* discouraged. – VLAZ Mar 04 '20 at 14:14
  • 6
    Using `for..in` to get an array's content is also discouraged. Use `for..of` instead. See [Why is using “for…in” with array iteration a bad idea?](https://stackoverflow.com/q/500504/215552) – Heretic Monkey Mar 04 '20 at 14:16
  • 1
    See also: https://stackoverflow.com/questions/7141734/extending-core-types-without-modifying-prototype – Mitya Mar 04 '20 at 14:18

1 Answers1

0

You can use Object.defineProperty to create non-enumerable attributes of any object, including arrays. Remember in JavaScript, arrays are just objects with numbers for keys, which is why attributes you add to them come up in a forEach.

superluminary
  • 47,086
  • 25
  • 151
  • 148