2

This is a beginner's question and the context doesn't really matter, and neither whether it makes sense at all.

I want to create class properties with dynamic names within a method of the class. Essentially something like this (the code does not work, of course):

class Trial {
    set_dynamic_property(name, value) {
        this.setAttribute(name, value)
    }
}

How do I achieve this?

1
  • You want to make class property or object property? Commented May 2, 2020 at 9:35

1 Answer 1

2

Use property accessors.

class Trial {
    set_dynamic_property(name, value) {
        this[name] = value;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this works! I thought I had tried exactly this, but I must have messed up something.
Great to hear that. Please accept this answer if it solved your problem. 😁

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.