如何引用给定名称的 class 作为字符串?
How do I refer to a class given its name as a string?
在 Perl 中:
package Foo {
sub new { bless {} }
sub some_method { 42 }
}
my $f = "Foo"->new;
say ref $f; # 'Foo'
$f->some_method;
在Python中:
class Foo:
def some_method():
return 42
f = globals()['Foo']()
print(type(f).__name__) # 'Foo'
f.some_method
在Ruby中:
class Foo
def some_method
return 42
end
end
f = Module.const_get('Foo').new
puts f.class # 'Foo'
f.some_method
在Javascript中:
class Foo {
some_method() { return 42 }
}
let f = new ?????????????;
console.log(f.constructor.name); // 'Foo'
f.some_method();
如果 Foo 是一个普通函数而不是 class,this["Foo"]
可以工作,但是您如何处理 classes?我尝试了 eval
,但是 f
实例不会存在于范围之外,因此该解决方案通常不适用。
编辑以解决可能的重复问题:工厂、注册表等仅在我可以引用工厂中现有的 class 时才起作用,但如果我想引用的 class 是事先不知道,我不能使用这个解决方法。
我建议使用一些变量进行映射:-
class Foo{
a(){}
}
var class_map = {
"Foo" : Foo
}
var f = new class_map['Foo']()
它指定
globally-declared classes are globals, but not properties of the
global object...
因此,您必须显式映射
从复制了相关部分:
class Foo {
some_method() { return 42 }
}
let f = new(eval('Foo'));
console.log(f.constructor.name); // 'Foo'
f.some_method();
请为原始答案投票。
在 Perl 中:
package Foo {
sub new { bless {} }
sub some_method { 42 }
}
my $f = "Foo"->new;
say ref $f; # 'Foo'
$f->some_method;
在Python中:
class Foo:
def some_method():
return 42
f = globals()['Foo']()
print(type(f).__name__) # 'Foo'
f.some_method
在Ruby中:
class Foo
def some_method
return 42
end
end
f = Module.const_get('Foo').new
puts f.class # 'Foo'
f.some_method
在Javascript中:
class Foo {
some_method() { return 42 }
}
let f = new ?????????????;
console.log(f.constructor.name); // 'Foo'
f.some_method();
如果 Foo 是一个普通函数而不是 class,this["Foo"]
可以工作,但是您如何处理 classes?我尝试了 eval
,但是 f
实例不会存在于范围之外,因此该解决方案通常不适用。
编辑以解决可能的重复问题:工厂、注册表等仅在我可以引用工厂中现有的 class 时才起作用,但如果我想引用的 class 是事先不知道,我不能使用这个解决方法。
我建议使用一些变量进行映射:-
class Foo{
a(){}
}
var class_map = {
"Foo" : Foo
}
var f = new class_map['Foo']()
globally-declared classes are globals, but not properties of the global object...
因此,您必须显式映射
从
class Foo {
some_method() { return 42 }
}
let f = new(eval('Foo'));
console.log(f.constructor.name); // 'Foo'
f.some_method();
请为原始答案投票。