How to Intercept Property Enumeration of an Object?

Viewed 63

I need to intercept property enumeration of an object (of a certain class) when iterating with a for..in loop. All I need to know is whether the object has been accessed in a for..in loop or not.

const myObject = new MyClass();
myObject["prop1"] = "val1";
myObject["prop2"] = "val2";
for (const p in myObject) {
    console.info(p + ": " + myObject[p]);
}

Expected output:

object enumerated
prop1: val1
prop2: val2

I do have full control over the class of the objects. It doesn't need to work with any object type.

This would be normally done using proxies. Unfortunately the JS engine I am using has a bug that makes that impossible. Are there any other options? Maybe overriding the getOwnPropertyNames() method of MyClass?

1 Answers

Are there any other options?

No. Only a proxy can trap the for … in enumeration itself.

Depending on your actual needs, you might be able to devise a hack with getters.

Maybe overriding the getOwnPropertyNames() method of MyClass?

Object.getOwnPropertyNames is a static method of Object, not a method of your class, and does not take part in a for … in loop.

Related