In Perl:
package Foo {
sub new { bless {} }
sub some_method { 42 }
}
my $f = "Foo"->new;
say ref $f; # 'Foo'
$f->some_method;
In Python:
class Foo:
def some_method():
return 42
f = globals()['Foo']()
print(type(f).__name__) # 'Foo'
f.some_method
In Ruby:
class Foo
def some_method
return 42
end
end
f = Module.const_get('Foo').new
puts f.class # 'Foo'
f.some_method
In Javascript:
class Foo {
some_method() { return 42 }
}
let f = new ?????????????;
console.log(f.constructor.name); // 'Foo'
f.some_method();
If Foo were a plain function and not a class, this["Foo"]
would work, but how do you deal with classes? I tried eval
, but the f
instance will not exist outside the scope, so that solution is not generally suitable.
Edit to address possible duplicates: Factories, registries and the like only work when I can refer to an existing class in the factory, but if the classes I want to refer to are not known in advance, I cannot use this work-around.