1

I have 2 function constructors in my javascript project. Like below

function Test(){
this.x = 45;
}

function S(){ 
this.y=78; 
this.f = new Test()
}

Now i have to access the property of 'S' on basis of type rather then by name. This is because there is a config file in my system which lists the variable to access in an object format like

[<Object of TYPE to create>,<Object of TYPE to access from created object>]

[S<classname>,Test<property type>]

Above means I have to create an Object of type "S" and access the TEST type property from created object. So far i have been doing below

let s1 = new S()
s1[Object.keys(s1).filter(item=>s1[item] instanceof Test)[0]]

However, i am worried my Class may contain 15-20 variables of different type and doing this repetitively for every other configuration object may not be a good practice. Is there some other way that i am not looking at to make above job easier?

Avij
  • 684
  • 7
  • 17

1 Answers1

0

I am thinking in this way. Your code works well until the types defined in your application become a larger group and you want to avoid a chain of conditioning.

Without the knowledge of how your application reads the config file, and how your object is structured, the below only works if Test() is under global scope.

To extract the right hand side of instanceof to become a variable, instead of a hardcoded function name. we can do

s1[Object.keys(s1).filter(item=>s1[item] instanceof eval("Test"))[0]]

or

s1[Object.keys(s1).filter(item=>s1[item] instanceof window["Test"])[0]]

substitute the "Test" literal with the configuration you read from the file.

The first method dynamic evaluates JavaScript code represented in string so it will return a Test() function.

The second method takes the property of name "Test" defined in the window object, which is function Test().

Mr. Brickowski
  • 1,134
  • 1
  • 8
  • 20
  • The config file is read as json, using http requests. However, there are certain guidelines on using eval in the code base which i assume are derived from https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – Avij Jul 27 '18 at 03:31