JavaScript中的动态实例化 [英] Dynamic instantiation in JavaScript

查看:69
本文介绍了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中的动态实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆