Is there a syntax/API/idiom in JavaScript to get a function that instantiates a type, for any type?
That is, replace a call to new Type(..args)
with, for instance, (pseudocode) Type.new(...args)
so that I can pass the function object as a parameter?
I've tried using const newTypeAsFn = new Type
on its own (without parentheses), but it still results in a constructor call instead of returning a function object that can be passed as a parameter and called later.
This is an example of what I wanted to be able to do:
const newStringAsFn = String.new;
[1, 2, 3].map(newStringAsFn);
// [String {"1"}, String {"2"}, String {"3"}]
I came up with a function that does that:
const newAsFn = (type) => (...args) => new type(...args);
That can be used like this:
const newStringAsFn = newAsFn(String);
[1, 2, 3].map(newStringAsFn);
Is there a way to do that without using this (possibly buggy) function I made up? A convention? Popular library method?