Justification of a call to "new type ()" in JavaScript

Is there any syntax / API / idiom in JavaScript to get a function that instantiates a type for any type?

That is, replace the call new Type(..args)with, for example, (pseudocode) Type.new(...args)so that I can pass the object to the function as a parameter?

I tried using it on my const newTypeAsFn = new Typeown (without parentheses), but it still calls the constructor 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 do:

const newStringAsFn = String.new;
[1, 2, 3].map(newStringAsFn);
// [String {"1"}, String {"2"}, String {"3"}]

I came up with a function that does this:

const newAsFn = (type) => (...args) => new type(...args);

This can be used as follows:

const newStringAsFn = newAsFn(String);
[1, 2, 3].map(newStringAsFn);

(, ) , ? ? ?

+4
2

Function.prototype getter, , .

// Your 'new' getter
Object.defineProperty(Function.prototype, "new", {
   get: function() {
     return (...args) => new this(...args)
   }
})


// Call it just like you show. It returns a function that invokes `new String`
const newStringAsFn = String.new;
const res = [1, 2, 3].map(newStringAsFn);

console.log(res);
Hide result

this, , new. , new args.


Reflect.construct.

// Your 'new' getter
Object.defineProperty(Function.prototype, "new", {
   get: function() {
     return (...args) => Reflect.construct(this, args)
   }
})


// Call it just like you show. It returns a function that invokes `new String`
const newStringAsFn = String.new;
const res = [1, 2, 3].map(newStringAsFn);

console.log(res);
Hide result
+2

, newAsFn. , :

let newAsFn = (type, numberOfArgs) =>
    (...args) => new type(...args.slice(0, numberOfArgs));

, , . :

let strings = [1, 2, 3].map(newAsFn(String, 1));

let newArray = newAsFn(Array, Infinity);
let arr1 = newArray(1, 2, 3, 4, 5),
    arr2 = newArray("Hello", "world", "!");
+1

Source: https://habr.com/ru/post/1696371/


All Articles