JS: Reflect .getOwnPropertyDescriptor
(new in ECMAScript 2015)
Reflect.getOwnPropertyDescriptor
Reflect.getOwnPropertyDescriptor(obj, key)-
- Return the Property Attributes in the form of Property Descriptor.
- If the property doesn't exist, returns
undefined. - If obj is not an object, throw TypeError.
const jj = { dog: 4 }; const xout = Reflect.getOwnPropertyDescriptor(jj, "dog"); console.log(xout); // { value: 4, writable: true, enumerable: true, configurable: true }
Example. check if a property is enumerable
// check if a property is enumerable console.assert( Reflect.getOwnPropertyDescriptor({ dog: 4 }, "dog").enumerable, );
Example. non-exist key
// non-exist key console.assert( Reflect.getOwnPropertyDescriptor({ dog: 4 }, "yyyyy") === undefined, );
Object .getOwnPropertyDescriptor vs Reflect .getOwnPropertyDescriptor
Object .getOwnPropertyDescriptor is older. It has a problem when the argument is a primitive type. It implicitly convert it to a object.
Reflect .getOwnPropertyDescriptor is new. Also, it is a replacement for Object.prototype.propertyIsEnumerable because that won't work if object has the same property name.