I want to get the object properties that were defined via Object.defineProperty
method.
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.
obj
- The object on which to define the property.prop
- The name of the property to be defined or modified.descriptor
: The descriptor for the property being defined or modified.
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?
Setting enumerable
to true
, will make it an enumerable
property:
> 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.Defaults to
false
.
Both your question and your answer can be improved :
Your question is either :
Object.defineProperty
? Answer : by setting, in the property parameters 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.