2

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.

daxim
  • 39,270
  • 4
  • 65
  • 132

2 Answers2

-2

What I suggest is use some variable for mapping :-

class Foo{
 a(){}
}

var class_map = {
 "Foo" : Foo
}

var f = new class_map['Foo']()

Here it specifies that

globally-declared classes are globals, but not properties of the global object...

Hence, you have to map explicitly

Community
  • 1
  • 1
Anmol Mittal
  • 843
  • 5
  • 12
-2

Copied the relevant part from https://stackoverflow.com/a/40069309/46395:

class Foo {
    some_method() { return 42 }
}

let f = new(eval('Foo'));
console.log(f.constructor.name);    // 'Foo'
f.some_method();

Please go upvote that original answer.

Community
  • 1
  • 1
daxim
  • 39,270
  • 4
  • 65
  • 132