Reputation: 149
I have a constructor for parent:
function genshinImpactCharacter(weapon, vision, rarity) {
this.weapon = weapon;
this.vision = vision;
this.rarity = rarity;
}
Later I create an object with the new
keyword:
const Sucrose = new genshinImpactCharacter('Catalyst', 'Anemo', 4);
I am trying to use defineProperty to add property favFlower: "Sweet Flower"
Object.defineProperty(Sucrose, "favFlower", {
name: 'Sweet Flower',
});
However, when I am trying to access favFlower
, it returns undefined
. As well, when I print the whole object in the console, this property remains undefined
.
Where did I make the mistake?
Upvotes: 0
Views: 276
Reputation: 56770
You need to make the property enumerable
(which defaults to false
) to see it when inspecting the object. Also you want to set value
of the property, not name
:
function genshinImpactCharacter(weapon, vision, rarity) {
this.weapon = weapon;
this.vision = vision;
this.rarity = rarity;
}
const Sucrose = new genshinImpactCharacter('Catalyst', 'Anemo', 4);
Object.defineProperty(Sucrose, 'favFlower', {
value: 'Sweet Flower',
enumerable: true,
});
console.log(Sucrose);
Please also note that by default properties added with Object.defineProperty()
are not writable
(writable: false
again is the default), so with the current code you cannot assign to the property later. Trying to do so will fail silently in non-strict mode, and throw an error in strict mode.
As a last note, by default properties added with Object.defineProperty()
are not configurable
(configurable: false
again is the default), so with the current code you cannot delete
the property or change it using Object.defineProperty()
on that object with the same property name again. Trying to do so will fail silently in non-strict mode, and throw an error in strict mode.
For more information, please consult https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
Upvotes: 4