简体   繁体   English

JavaScript:如何在不使用Object.defineProperty的情况下定义不可枚举的方法?

[英]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. 我想为Object添加一个方法,但现在所有的数组和对象都有它。 When I use for(.. in ..) , it is enumarated and this is a problem for my software. 当我使用for(.. in ..) ,它被驱使,这对我的软件来说是一个问题。 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. 我知道有一个Object.defineProperty() ,但它不受旧浏览器(仍然存在)甚至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 . 不。这就是为什么在没有立即检查hasOwnProperty情况下使用JavaScript for..in被认为是不好的做法。 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. 如果在没有hasOwnProperty检查的情况下使用for..in JSLint等工具将在代码中报告错误。

For ECMAScript 3 (used in old browser), you cannot change the enumerable attribute. 对于ECMAScript 3(在旧浏览器中使用),您无法更改可枚举属性。
If you want to filter the method, maybe you can check the type of the object in for(..in..). 如果要过滤方法,也许可以检查对象的类型(.. in ..)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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