Question

I have extended Array prototype:

if(typeof Array.prototype.filter === 'undefined') Array.prototype.filter = function(fun /*, thisp*/){
  var len = this.length;
  if(typeof fun != "function") throw new TypeError();

  var res = [], thisp = arguments[1];

  for(var i=0;i<len;i++){
    if(i in this){
      var val = this[i]; // in case fun mutates this
      if(fun.call(thisp, val, i, this)) res.push(val);
    }
  }

  return res;
};

For example I have created array:

var A = [ 1, 2, 3, 4, 5 ];

Then I added extra properties to it, that I will use:

A.creator = 'Rustam';
A.created = new Date();

If I will use for-in loop, and browser has not built-in support for Array.filter, it will go through A.filter.

I know this way:

for(var p in A) {
  if (!A.hasOwnProperty(p)) continue
  console.log(p)
};

Is there a way to make A.filter hidden in for-in without using hasOwnProperty?


UPDATE to answer. Browser support:

  • IE9+
  • FF4+
  • Chrome
  • Opera 11.6+
  • Safari 5+
Was it helpful?

Solution

To define a property which does not show up in loops, use Object.defineProperty:

Object.defineProperty(Array.prototype, 'filter', {value:'XYZ'});

This extends Array.prototype with a property called filter with default property descriptors, including enumerable: false, which causes the property to not show up in for( .. in ..) loops.

References

PS: Will not work on older browsers I don't have the browser compatibility matrix for this API.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top