Home > Enterprise >  How can we generalize the constructor with the variable formatting in Javascript?
How can we generalize the constructor with the variable formatting in Javascript?

Time:12-22

Suppose,

My Code:

var slist = ['ec', 'ce', 'ke']

for(let s in slist){ const s1 = slist[s]

//here, AWS is class Name and it has methods which are in slist.

const ec2 = new AWS.s1() }

Requirement: Now, when creating the constructor with the methods of AWS class, I want that s1 variable which is having method name should create a constructor.

CodePudding user response:

If AWS.ec, AWS.ke, AWS.ce are the properties used when hard-coded, you can access then via a variable using square-bracket notation

const slist = ['ec', 'ce', 'ke']

slist.forEach(s => {
  const ec2 = new AWS[s]()
  • Related