javascript 从动态类名创建对象 - JS 中的 ReflectionClass?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5085095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:54:04  来源:igfitidea点击:

create object from dynamic classname - ReflectionClass in JS?

javascript

提问by kubi

is it possible to do something like this without evil eval:

是否有可能在没有邪恶 eval 的情况下做这样的事情:

var str='MyClass';
eval('new '+str);

i just learned that there's ReflectionClass in PHP... thanks.

我刚刚了解到 PHP 中有 ReflectionClass...谢谢。

回答by Jacob Relkin

You could try this:

你可以试试这个:

var str = "MyClass";
var obj = new window[str];

Here's an example:

下面是一个例子:

function MyClass() {
   console.log("constructor invoked");
}

var s = "MyClass";
new window[s]; //logs "constructor invoked"

回答by Mykhaylo Adamovych

Create object (invoke constructor) via reflection:

通过反射创建对象(调用构造函数):

SomeClass = function(arg1, arg2) {
    // ...
}

ReflectUtil.newInstance('SomeClass', 5, 7);

and implementation:

和实施:

/**
 * @param strClass:
 *          class name
 * @param optionals:
 *          constructor arguments
 */
ReflectUtil.newInstance = function(strClass) {
    var args = Array.prototype.slice.call(arguments, 1);
    var clsClass = eval(strClass);
    function F() {
        return clsClass.apply(this, args);
    }
    F.prototype = clsClass.prototype;
    return new F();
};