Federico Razzoli
Federico Razzoli

Reputation: 5391

JavaScript: How to Define a Non-Enumerable Method without using Object.defineProperty?

I want to add a method to Object, but now all arrays and object have it. When I use for(.. in ..), it is enumarated and this is a problem for my software. So, I need to make my method non-enumerable.

I know there is a Object.defineProperty(), but it is not supported by old browser (which are still around) and even latest versions of Konqueror.

Is there another way to make a method non-enumerable?

Upvotes: 4

Views: 612

Answers (2)

daleqq
daleqq

Reputation: 366

For ECMAScript 3 (used in old browser), you cannot change the enumerable attribute.
If you want to filter the method, maybe you can check the type of the object in for(..in..).

Upvotes: 0

Joe White
Joe White

Reputation: 97818

No. That's why it's considered bad practice to use JavaScript's for..in without immediately checking for hasOwnProperty. I.e., you should always do:

for (var item in obj) {
    if (obj.hasOwnProperty(item)) {
        // ...
    }
}

Tools like JSLint will report an error in your code if you use for..in without a hasOwnProperty check.

Upvotes: 3

Related Questions