Martin
Martin

Reputation: 1419

Don't want to use eval when instantiating object from String - help?

I have the following legacy code that I'd like to remove eval from:

eval('view = new ' + o.base + '(o)');

The best I've come up with so far is ...

view = eval(o.base).prototype.constructor.apply(o)

... which obviously still uses eval. Can someone please help?

NOTE: The o.base variable is a qualified classname (e.g. "application.area.type.ClassName") referring to a valid function.

Upvotes: 1

Views: 230

Answers (1)

davin
davin

Reputation: 45525

view = application.area.type[o.base].prototype.constructor.apply(o);

But you can still use new:

view = new application.area.type[o.base](o);

UPDATE

A more generic way to achieve this for o.base representing any qualified name would be:

var base = window;
for(var i=0,ns=o.base.split('.'); i<ns.length; ++i) {
   base = base[ns[i]];
}
view = new base(o);

Upvotes: 3

Related Questions