A
A
Alexey Ivanov2015-01-15 05:30:31
JavaScript
Alexey Ivanov, 2015-01-15 05:30:31

How to add a method to an object so that it is not visible when iterating over objects?

Good morning!
There is an object testObj with the count method added, when we iterate over it, we get: count, p1 and p2.
How to remove the added count method from this list? (You can, of course, check the type of the value of the property for the function, but this will have to be done every time the object is iterated, which is not good)

Object.prototype.count = function() {
  var count = 0;
  
  for(var key in this) {
    count++;
  }
  
  return count;
}

var testObj = {'p1': 124, 'p2': 6231};

for(var key in testObj) {
  console.log(key);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GeraldIstar, 2015-01-15
@Kandiar

For older versions of JS, or rather ECMAScript 3, the one in IE8:
Extend object, without the fact that the added properties are not enumerable - will not work.
In such cases, and indeed when using for ... in , usually each property is checked against hasOwnProperty

for (var key in testObj) {
  if (!testObj.hasOwnProperty(key)) continue;
  //Тут мог быть ваш код 
}

Somehow it seems to be.
There is information on this topic here:
learn.javascript.ru/native-prototypes
If you do not need to support old browsers, there is Object.defineProperty()
Object.defineProperty( Object.prototype, 'count' {
    value: function count() { /* тело функции */ },
    enumerable: false
});

The enumerable descriptor allows, depending on the value, to make the property enumerable or not, when traversing the object in the for ... in loop.
habrahabr.ru/post/150571

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question