简体   繁体   中英

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?

No. That's why it's considered bad practice to use JavaScript's for..in without immediately checking for hasOwnProperty . Ie, 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM