0

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?

1
  • If you don't mind the property been mutated, in the same way weapon etc can be, why not just do Sucrose.favFlower = 'Sweet Flower'?? Commented Apr 9, 2021 at 15:23

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you a lot! Somehow, I decided that "value" may be replaced by the user's choice, but it would make no sense. As well, thanks for mentioning the enumerable property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.