[英]javascript property non enumerable still found by for… in
I'm writing a little javascript library: I've defined an Item
object, then added a function with Item.prototype.addNumber
and finally I set it as not enumerable, but if I try to log Item's method using for...in
loop the function still appears. 我正在写一个小的javascript库:我已经定义了一个Item
对象,然后添加了一个带有Item.prototype.addNumber
的函数,最后我把它设置为不可枚举,但是如果我尝试使用for...in
来记录Item的方法循环功能仍然出现。 This is my code, Am I doing something wrong? 这是我的代码,我做错了吗? (tested on Chrome 18 and Firefox 11) (在Chrome 18和Firefox 11上测试过)
function Item() {
...
}
Item.prototype.addString= function() {
...
}
Object.defineProperty(Item, "addString", { enumerable: false });
You're defining the property on Item
instead of on Item.prototype
. 您在Item
而不是Item.prototype
上定义属性。
Object.defineProperty(Item.prototype, "addString", { enumerable: false });
If you used Object.defineProperty
to initially add addString
to Item.prototype
, then you could explicitly (or implicitly) set the property descriptors at the same time... 如果您使用Object.defineProperty
最初将addString
添加到Item.prototype
,那么您可以显式(或隐式)同时设置属性描述符...
This will implicitly set enumerable:false
, as well as false
for configurable
and writable
. 这将隐式设置enumerable:false
,以及writable
configurable
和writable
false
。
Object.defineProperty(Item.prototype, "addString", {
value: function() {
...
}
});
Or if you wanted only enumerable
to be false
, you could do this... 或者,如果你只想要enumerable
为false
,你可以这样做......
Object.defineProperty(Item.prototype, "addString", {
value: function() {
...
},
configurable: true,
writable: true
// ,enumerable: false // uncomment to be explicit, though not necessary
});
You are defining a property ( addString
) directly on Object
(the non enumerable one) and another addString
(enumerable by default) on the Item
's prototype. 您正在Item
的原型上直接在Object
(非可枚举的)和另一个addString
(默认为可枚举)上定义属性( addString
)。
A for ( in )
iterates over properties up the prototype chain, that's why it appears there. for ( in )
迭代原型链上的属性,这就是它出现的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.