-1

I have two functions nameFuncOne and nameFuncTwo that i represented in my code.

this.mainFunction = function() {
    this.someFunc = function() {
    return this.name;
  }
};

this.nameFuncOne = function() {
    this.name = "nameOne";
    mainFunction.call(this);
};
this.nameFuncTwo = function() {
    this.name = "nameTwo";
    mainFunction.call(this);
};
var one = new nameFuncOne();
var two = new nameFuncTwo();
console.log(one.someFunc() + "  " + two.someFunc());

so here what i did is assigning constructor functions nameFuncOne and nameFuncTwo into the variables one and two. so why i cant create something like this.

var funcArr = ["new nameFuncOne()", "new nameFuncTwo()"];
var arr = [];
for (var i=0;i<funcArr.length; i++) {
    arr[i] = funcArr[i];
  //console.log(arr[i].someFunc())
}

my question is i dont want to create variables manually. is there any way to do this. please correct me if i went wrong.

htoniv
  • 1,658
  • 21
  • 40

1 Answers1

1

yes yo can do like that, but there is problem in your code. you store string into array.

try this,

var funcArr = ["new nameFuncOne()", "new nameFuncTwo()"];
var arr = [];
for (var i=0;i<funcArr.length; i++) {
    arr[i] = eval(funcArr[i]);
     console.log(arr[i].someFunc())
}

The eval() function evaluates JavaScript code represented as a string. LINK

another way:

var funcArr = [new nameFuncOne(), new nameFuncTwo()];
    var arr = [];
    for (var i=0;i<funcArr.length; i++) {
        arr[i] = funcArr[i];
         console.log(arr[i].someFunc())
    }
i'm PosSible
  • 1,373
  • 2
  • 11
  • 30
  • yes eval is bad idea,it opens up your code for injection attacks. but you store string in array so you have to execute it. – i'm PosSible Mar 21 '16 at 06:38