[英]Why can't I enumerate object property defined as not enumerable?
I want to get the object properties that were defined via Object.defineProperty
method. 我想获取通过
Object.defineProperty
方法定义的对象属性。
Object.defineProperty(obj, prop, descriptor)
The
Object.defineProperty()
method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.Object.defineProperty()
方法直接在对象上定义新属性,或修改对象上的现有属性,然后返回该对象。
obj
- The object on which to define the property.obj
在其上定义属性的对象。prop
- The name of the property to be defined or modified.prop
要定义或修改的属性的名称。descriptor
: The descriptor for the property being defined or modified.descriptor
:定义或修改的属性的描述符。
So, let's take an example: 因此,让我们举个例子:
> a = {}
{}
> a.foo = "bar"
'bar'
> Object.keys(a)
[ 'foo' ]
> Object.defineProperty(a, "bar", { get: function () { return "foo"; }})
{ foo: 'bar' }
> a.bar
'foo'
> a.foo
'bar'
> Object.keys(a)
[ 'foo' ]
> for (k in a) { console.log(k); }
foo
In the for loop thing, how can I list the bar
property (that was defined with defineProperty
function? 在for循环中,如何列出
bar
属性(使用defineProperty
函数定义的属性?
Setting enumerable
to true
, will make it an enumerable
property: 将
enumerable
设置为true
,将使其成为enumerable
属性:
> Object.defineProperty(a, "b", { enumerable: true, get: function () { return "foo"; }})
{ foo: 'bar', b: [Getter] }
> for (k in a) { console.log(k); }
foo
b
> Object.keys(a)
[ 'foo', 'b' ]
true
if and only if this property shows up during enumeration of the properties on the corresponding object.当且仅当在枚举相应对象的属性时显示此属性时,才返回
true
。Defaults to
false
.默认为
false
。
Both your question and your answer can be improved : 您的问题和答案都可以得到改善:
Your question is either : 您的问题是:
Object.defineProperty
? Object.defineProperty
定义可枚举的属性? Answer : by setting, in the property parameters enumerable:true
答:通过设置,在属性参数中
enumerable:true
OR 要么
Answer : by using Object.getOwnPropertyNames
, which will perform quite like keys
, except... all own properties are returned, meaning : including the non-enumerable properties but not including prototype's properties (and obviously, no properties from the prototype chain). 答案:通过使用
Object.getOwnPropertyNames
,它将执行与keys
非常相似的操作,除了...返回所有自己的属性,这意味着: 包括不可枚举的属性,但不包括原型的属性(显然,原型链中没有任何属性)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.