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

发布于 2024-12-20 13:44:29 字数 217 浏览 5 评论 0原文

我想向对象添加一个方法,但现在所有数组和对象都有它。当我使用 for(.. in ..) 时,它被枚举,这对我的软件来说是一个问题。所以,我需要使我的方法不可枚举。

我知道有一个 Object.defineProperty(),但旧浏览器(仍然存在)甚至最新版本的 Konqueror 都不支持它。

还有另一种方法可以使方法不可枚举吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

变身佩奇 2024-12-27 13:44:29

不。这就是为什么在不立即检查 hasOwnProperty 的情况下使用 JavaScript 的 for..in 被认为是不好的做法。也就是说,您应该始终这样做:

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

如果您将 用于..在 中,没有 hasOwnProperty 检查。

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.

笔落惊风雨 2024-12-27 13:44:29

对于 ECMAScript 3(在旧浏览器中使用),您无法更改可枚举属性。
如果你想过滤方法,也许你可以检查 for(..in..) 中对象的类型。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文