Skip to content
Advertisement

JavaScript: Is there an equivalent to the Python setattr() function?

I have a class to which I would like to include a method of overriding some of the default instance variables in the constructor, without having a dozen parameters. I would like to do this by passing an object in the form of:

JavaScript

In Python this could be done with

JavaScript

Is there a JS equivalent or do I just have to add a bunch of parameters with default values?

Advertisement

Answer

For your given example you simply need to use bracket notation to access a property from a variable.

JavaScript

An alternative would be to destructure the needed parameters from the overrides object setting appropriate defaults, and leaving the ...rest for use elsewhere.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement