简体   繁体   English

为什么不能枚举定义为不可枚举的对象属性?

[英]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' ]

enumerable

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 : 您的问题是:

  • How can i define an enumerable property using Object.defineProperty ? 如何使用Object.defineProperty定义可枚举的属性?

Answer : by setting, in the property parameters enumerable:true 答:通过设置,在属性参数中enumerable:true

OR 要么

  • How can i retrieve a property that was defined on an object as non enumerable ? 我如何检索在对象上定义为不可枚举的属性?

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.

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