I will be very obliged if u help me to realize why properties that can be shown by method getOwnPropertyDescriptor cannot be outputted by usual console.log. And waiting for your explanations why node 18.0 gets crazy about Object.create() and I cannot output the properties in anyway ^_^
//Usual option
console.log('[MyObject1]')
const MyObject = {text: null};
console.log("MyObject: ", MyObject); // all right
console.log('[MyObject2]')
const MyObject2 = {};
Object.defineProperty(MyObject2, 'text' , {value: null});
console.log(MyObject2) // why nothing ?
console.log(MyObject2.text) // it is
console.log(Object.getOwnPropertyDescriptor(MyObject2, 'text')); // And descriptor is too
console.log('[MyObject3]')
const MyObject3 = Object.create({text: null});
console.log(MyObject3) // it can be or not it depeneds on node compiler...
console.log(MyObject3.text) // Again it is
console.log(Object.getOwnPropertyDescriptor(MyObject3, 'text')); // Why undefined ?
// P. S.
// I have no ideas why no output by console.log() and no descriptor in VS Code
CodePudding user response:
By default, properties added on the objects using Object.defineProperty
method are not enumerable. You have to explicitly set the property to be enumerable.
const MyObject2 = {};
Object.defineProperty(MyObject2, 'text', {
value: null,
enumerable: true
});
console.log(MyObject2);
In the last code example, text
is defined in the prototype object of the MyObject3
and as Object.getOwnPropertyDescriptor
returns own properties, not the inherited ones, text
is not returned by this method.
const MyObject3 = Object.create({text: null});
const MyObject3Proto = Object.getPrototypeOf(MyObject3);
console.log(Object.getOwnPropertyDescriptor(MyObject3Proto, 'text'));