monade
monade

Reputation: 333

JavaScript - set class properties dynamically inside class method

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?

Upvotes: 2

Views: 1615

Answers (1)

D. Pardal
D. Pardal

Reputation: 6587

Use property accessors.

class Trial {
    set_dynamic_property(name, value) {
        this[name] = value;
    }
}

Upvotes: 2

Related Questions