开发者

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

开发者 https://www.devze.com 2023-03-13 22:39 出处:网络
I have the following legacy code that I\'d like to remove eval from: eval(\'view = new \' + o.base + \'(o)\');

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.bas开发者_如何学Pythone).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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消