Send constructor as parameter

One of the nice things about Javascript is the ability to send functions as parameters. I have an application in which I need to send classes as parameters.

As a simple example, I need a function that does some tests for a class, and I want to send the class as a parameter:

test(ClassA); test(ClassB); 

where ClassA and ClassB are two different classes.

The first possible solution:

 function test(theClass) { var object1 = new theClass(); var object2 = new theClass(); assert(object1.toString()===object2.toString()); // ... more asserts ... } 

This works well, but it does not allow me to send parameters to build classes. For example, ClassA may have several initialization parameters, and I can test each option separately.

Second possible solution:

 function test(theClass, theInitializationOptions) { var object1 = new theClass(theInitializationOptions); var object2 = new theClass(theInitializationOptions); assert(object1.toString()===object2.toString()); // ... more asserts ... } 

What can I use as follows:

 test(ClassA, {option1: 1, option2: 2...}); test(ClassA, {option1: 2, option2: 3...}); test(ClassB, {}); 

This works well, but it is cumbersome - it requires me to send two parameters, and if the "test" function uses sub-functions, it will have to send these two parameters all the way down. I am looking for a function 'test' that takes only one parameter.

The third possible solution is to send an initialization function instead of a class:

 function test(theClassConstructor) { var object1 = theClassConstructor(); var object2 = theClassConstructor(); assert(object1.toString()==object2.toString()); } 

What can I use as follows:

 test(function() { return new ClassA(1,2,3); }) /* test class A */ test(function() { return new ClassB(4,5); }) /* test class B */ 

The problem is that this test function accepts a function instead of a class.

I am looking for a function 'test' that takes a class as an argument (that is, it initializes a new object using the "new" operator), but still allows the caller to pass arguments along with the class.

In other words, I'm looking for a way to bind arguments to a constructor.

Is this possible in Node.js?

+4
source share
1 answer

You can use the # bind function to do this,

 test(MyClass.bind(this, 1, 2, 3)); function test(klass) { var c = new klass(); /* stuff */ } 

The first this parameter is ignored when using the new keyword.

+1
source

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


All Articles