本文介绍了JavaScript中的动态实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
除了eval之外,还有其他方法可以使用变量参数列表来实例化对象吗?
Apart from eval, is there any other way to instantiate an object using variable argument list?
例如: var foo = instantiate(className) ,[arg1,arg2,...])
推荐答案你可以用一个实例化一个对象变量参数列表如下:
You can instantiate an object with a variable argument list like this:
function instantiate(className, args) { var o, f, c; c = window[className]; // get reference to class constructor function f = function(){}; // dummy function f.prototype = c.prototype; // reference same prototype o = new f(); // instantiate dummy function to copy prototype properties c.apply(o, args); // call class constructor, supplying new object as context o.constructor = c; // assign correct constructor (not f) return o; }
附注:你可以希望传递对类构造函数的直接引用:
Side note: you may wish to pass a direct reference to the class constructor function:
var foo = instantiate(Array, [arg1, arg2, ...]); // Instead of: var foo = instantiate("Array", [arg1, arg2, ...]);...这使得它与非全局函数兼容。
... which makes this compatible with non-global functions.
更多推荐
JavaScript中的动态实例化
发布评论