Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call string constructor function

Tags:

javascript

I have a constructor function, for example webapp.core.cf1 or Backbone.Router. But I get this constructor function not as a reference, but as a string! I cannot change this requirement, the constr. must be in a string. How can I make a new object from this, for instance classfun("Backbone.Router")?

function classfun (cfstr) 
{ 
  ...
  cf = new window[cfstr]();

If I try it this way, I get the error: ... is not a constructor.

Why this does not work? Is there an alternative way without using eval()?

Thanks a lot in advance

EDIT

Thank you all for your answers!

Thank you, Tronix117, this was the problem!!

Thank you, Benjamin Schulte, for the function!

like image 514
Wolfgang Adamec Avatar asked Apr 12 '26 06:04

Wolfgang Adamec


1 Answers

If you try in your console:

var A=function(a){this.test=a};
b = new window["A"](3);
console.log(b.test); // return 3

So that means, you are trying to access something which is not in the scope of window, it should rather be something like that: window.something["A"], if you don't know what is something then you should use the function of Benjamin, otherwise use this one, because it's way faster.

like image 88
Tronix117 Avatar answered Apr 20 '26 12:04

Tronix117