Answer the question
In order to leave comments, you need to log in
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
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;
//Тут мог быть ваш код
}
Object.defineProperty( Object.prototype, 'count' {
value: function count() { /* тело функции */ },
enumerable: false
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question