JavaScript:如何在不使用 Object.defineProperty 的情况下定义不可枚举方法?
我想向对象添加一个方法,但现在所有数组和对象都有它。当我使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不。这就是为什么在不立即检查
hasOwnProperty
的情况下使用 JavaScript 的for..in
被认为是不好的做法。也就是说,您应该始终这样做:如果您将
用于..在
中,没有hasOwnProperty
检查。No. That's why it's considered bad practice to use JavaScript's
for..in
without immediately checking forhasOwnProperty
. I.e., you should always do:Tools like JSLint will report an error in your code if you use
for..in
without ahasOwnProperty
check.对于 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..).