Search code examples
javascriptarraysobjectenumerable

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?


Solution

  • 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.